how can I display category name of selected wallpaper - django

models.py
class Category(models.Model):
category_name = models.CharField(max_length=100)
def __str__(self):
return self.category_name
class SubCategory(models.Model):
sub = models.CharField(max_length=100)
category = models.ForeignKey(Category,on_delete=models.CASCADE)
def __str__(self):
return self.sub
class Wallpaper(models.Model):
subcategory = models.ManyToManyField(SubCategory)
this is my view.py
def download(request, wallpaper_name):
try:
wallpaper = Wallpaper.objects.get(name=wallpaper_name)
context = {'wallpaper': wallpaper}
return render(request, 'Wallpaper/download.html', context)
on my download page how can I show categorty name of that specific wallpaper

You can simply use this.
Check this out docs.
def download(request, wallpaper_name):
try:
wallpaper = Wallpaper.objects.get(name=wallpaper_name)
categories_name = wallpaper.subcategory.values_list(
"category__category_name",
flat=True
).distinct("category")
....

A quick and dirty solution is get all the subcategory from the wallpaper that you just found. Then get the category_name of each subcategory:
def download(request, wallpaper_name):
try:
wallpaper = Wallpaper.objects.get(name=wallpaper_name)
subcategories = wallpaper.subcategory.all()
category_names = [cat.category_name for cat in subcategories]

Related

How to reference a slug from a different model in get_success_url?

Setup
I have two models in my app. One is for a Journal and the other one is for entries to that journal. I wrote a CreateView class that will allow user to create a Journal entry for any Journal id currently located in. Ideally I want the class to "refresh" with the updated entry or in other words the get_success_url should lead the page we are currently located at.
views.py
class ToJournalEntriesList(LoginRequiredMixin, CreateView):
model = to_journal_entry
template_name = 'to_journals/to_journal_entries_list.html'
fields = ('body',)
def get_success_url(self):
return reverse('to-journals', kwargs={'slug':self.object.slug})
def form_valid(self, form):
current_journal = to_journal.objects.get(journal_user=self.request.user, slug=self.kwargs['slug'])
form.instance.journal_user = self.request.user
form.instance.journal_name = current_journal
return super(ToJournalEntriesList, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(ToJournalEntriesList, self).get_context_data(**kwargs)
context['to_journal_entries'] = to_journal_entry.objects.all()
return context
models.py
class to_journal(models.Model):
journal_name = models.CharField(max_length = 40)
slug = AutoSlugField(populate_from='journal_name')
date_created = models.DateTimeField(auto_now_add=True)
journal_user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,)
def __str__(self):
return str(self.journal_user) + " " + self.journal_name
def get_absolute_url(self):
return reverse('to-journals')
class to_journal_entry(models.Model):
body = models.TextField()
entry_date = models.DateTimeField(auto_now_add=True)
journal_name = models.ForeignKey(to_journal, on_delete=models.CASCADE,)
journal_user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,)
def __str__(self):
return str(self.journal_name) + " " + str(self.entry_date)
def get_absolute_url(self):
return reverse('to-journal-entries', args=(self.slug))
urls.py
urlpatterns = [
path('', CreateToJournal.as_view(), name='to-journals'),
path('<slug:slug>', ToJournalEntriesList.as_view(), name='to-journal-entries'),
]
Error
With the current setup that I have I get:
Which makes sense, because the to_journal_entry model does not have that that field.
Question
I am sure both my get_success_url() in views.py and get_absolute_url() in models.py are done incorrectly, but I could not find a good explanation of how those work. How should I set them up to achieve desired result? Thanks a ton in advance!
I appreciate everyone taking a look. Best, Rasul.
You can just follow the relationship:
def get_success_url(self):
return reverse('to-journals', kwargs={'slug': self.object.journal_name.slug})
Your self.object is a to_journal_entry. You probably want to use the to_journal, you can do that by obtaining the journal_name:
class ToJournalEntriesList(LoginRequiredMixin, CreateView):
model = to_journal_entry
template_name = 'to_journals/to_journal_entries_list.html'
fields = ('body',)
def get_success_url(self):
return reverse('to-journals', kwargs={ 'slug': self.object.journal_name.slug })
Note: usually the names of the models are written in PerlCase, so JournalEntry instead of to_journal_entry.

Django QuerySet returns nothing

I have a list of countries, they all have there own url www.example.com/al/ for example. There is a list of cities for every country but the object_list is empty
My View:
class CityOverview(generic.ListView):
template_name = 'shisha/pages/country_index.html'
model = City
def get_queryset(self, *args, **kwargs):
country_id = self.kwargs.get('country_id')
return City.objects.filter(country__name=country_id)
My Model:
class Country(models.Model):
COUNTRY_CHOICES = (
('al', 'Albania'),
('ad', 'Andorra'),
#etc. etc.
)
name = models.CharField(max_length=255, choices=COUNTRY_CHOICES, default='nl')
def __str__(self):
return self.name
class City(models.Model):
country = models.ForeignKey(Country, on_delete=models.CASCADE)
name = models.CharField(max_length=250)
def __str__(self):
return self.name
My Urls:
path('<str:country_id>', views.CityOverview.as_view(), name='country'),
My Template:
{{ object_list }}
It returns an empty QuerySet
<QuerySet []>
Does anyone know what the problem is?
The problem is you are trying to match country__name to country_id. Alter the last line in get_queryset to become return City.objects.filter(country__id=country_id) which will now filter the country_id supplied against City's country id.
May be your returning query is wrong,
class Country(Models.model):
country_id=Autofield()
country_name=CharaField()
in Views.py
def get_queryset(self, *args, **kwargs):
country_id = self.kwargs.get('country_id')
return City.objects.filter(country_id=country_id)

Django join button to goal

I try to create changing button after user join to Goal.
I have work buttons, but i don't know how to change this in template.
I try to do this with boolean field, when user click "Join", boolean field change to True, and then in template I try:
{% if goal.joined %}
<Delete join>
{% else %}
<join to goal>
{% endif %}
Models:
class Goal(models.Model, Activity):
title = models.CharField(max_length=255, verbose_name='Tytuł')
image = models.ImageField(upload_to='goals', verbose_name='Tło')
body = HTMLField(verbose_name='Treść')
tags = TaggableManager()
created_at = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
slug = AutoSlugField(populate_from='title')
def __str__(self):
return self.title
class Meta:
verbose_name = 'Cele'
ordering = ['-created_at']
def get_absolute_url(self):
return reverse('goaldetail', args=[str(self.slug)])
#property
def activity_actor_attr(self):
return self.author
def add_user_to_list_of_attendees(self, user):
registration = Joined.objects.create(user = user,
goal = self,
created_at = timezone.now())
def remove_user_from_list_of_attendees(self, user):
registration = Joined.objects.get(user = user, goal = self)
registration.delete()
class Joined(models.Model, Activity):
goal = models.ForeignKey(Goal, on_delete=models.CASCADE, related_name='joined')
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='joined_users')
created_at = models.DateTimeField(auto_now_add=True)
joined = models.BooleanField(default=False)
def save(self, *args, **kwargs):
if self.id is None and self.created_at is None:
self.created_at = datetime.datetime.now()
self.joined = True
super(Joined, self).save(*args, **kwargs)
#property
def activity_actor_attr(self):
return self.user
Views:
def joined_add(request, pk):
this_goal = Goal.objects.get(pk=pk)
this_goal.add_user_to_list_of_attendees(user=request.user)
return redirect('goaldetail', slug=this_goal.slug)
def joined_delete(request, pk):
this_goal = Goal.objects.get(pk=pk)
this_goal.remove_user_from_list_of_attendees(request.user)
return redirect('goaldetail', slug=this_goal.slug)
def goaldetail(request, slug):
goal = get_object_or_404(Goal, slug=slug)
return render(request, 'goals/detail.html',
{'goal': goal})
Path:
path('joined/<int:pk>', views.joined_add, name='joined_add'),
path('joined-delete/<int:pk>', views.joined_delete, name='joined_delete'),
Create and delete works perfect, but on template this button don't change. I try in many ways and don't know how to do this.

django multiple query filter - match 1 or 2 fields

I have a model like this:
class Result(models.Model):
title = models.CharField(max_length=300)
desc = models.TextField(max_length=800)
url = models.CharField(max_length=200)
rank = models.BigIntegerField()
category = models.ForeignKey('Category')
tags = TaggableManager()
def __str__(self):
return self.title
class Meta:
verbose_name_plural = "Risultati"
class Category(models.Model):
title = models.CharField(max_length=300)
slug = models.SlugField(null=True)
def __str__(self):
return self.title
class Meta:
verbose_name_plural = "Categorie"
and views:
def search_form(request):
return render(request, 'search.html')
def result(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
results = Result.objects.filter(tags__name__in=[q], desc__icontains=q).order_by('-rank')
return render(request, 'results.html', {'results': results, 'query': q})
else:
return render(request, 'search.html', {'error': True})
def detail(request, result_id):
try:
result = Result.objects.get(pk=result_id)
except Result.DoesNotExist:
raise Http404("Nessun risultato :(")
return render(request, 'detail.html', {'result': result})
i need to search by filter, tags OR desc, I try to concatenate the filter().filter() but nothing happen, where is the mistake?
Chaining expressions either in the same filter() or in separate ones performs an implicit AND. If you want to perform an OR or an explicit AND then you need to use Q objects instead.
....filter(Q(tags__name__in=[q]) | Q(desc__icontains=q))....

Accessing SubClassed User Profile Module in Django 1.3

I am trying to create two user types in django 1.3. I am subclassing the AUTH_PROFILE_MODULE with the following models.py:
class Member(models.Model):
ROLE_CHOICES = (
(0, 'Guide'),
(1, 'Operator'),
)
user = models.ForeignKey(User, unique=True)
location = models.CharField(max_length=60)
role = models.IntegerField(choices=ROLE_CHOICES)
class Guide(Member):
bio = models.TextField(blank=True)
experience = models.TextField(blank=True)
image = models.ImageField(blank=True, upload_to='images')
fileupload = models.FileField(blank=True, upload_to='files')
def __unicode__(self):
return self.user.username
def get_absolute_url(self):
return '/profiles/guides/%s' % self.user.username
class Operator(Member):
bio = models.TextField(blank=True)
image = models.ImageField(blank=True, upload_to='images')
def __unicode__(self):
return self.user.username
def get_absolute_url(self):
return '/profiles/operators/%s' % self.user.username
I am using generic class based views and can get the ListView to work for the Guide and Operator models I cannot get the DetailView to work. My views.py is as follows:
class GuideDetailView(DetailView):
model = Guide
context_object_name = 'guide'
template_name = 'members/guide_detail.html'
class GuideListView(ListView):
model = Guide
context_object_name = 'guides'
template_name = 'members/guide_list.html'
Any idea what might be missing?
Either provide a queryset:
class GuideDetailView(DetailView):
queryset = Guide.objects.all()
or override the get Method of DetailView:
class GuideDetailView(DetailView):
def get(self):
return "Everything you want, maybe: Guide.object.get(id=1)"
Given this in your urls.py:
url(r'^(?P<my_id>\d)/$', GuideDetailView.as_view(),),
You need to override get, like this:
class GuideDetailView(DetailView):
def get(self, request, **kwargs):
# lookup Guide Id in your database and assign it object
self.object = Guide.objects.get(pk=kwargs.get('my_id'))
# add object to your context_data, so that you can access via your template
context = self.get_context_data(object=self.object)
return self.render_to_response(context)