I'm trying to implement multi-language on my site using django-modeltranslation, but I can't filter product by category when switched to other languages, I'm using Python 3.10.6, Django 4.2, django-modeltranslation 0.18.9 my code:
model.py
class Category(models.Model):
name = models.CharField(max_length=100)
created_at = models.DateField(default=timezone.now)
class Meta:
verbose_name_plural = "Categories"
def __str__(self):
return self.name
class Course(models.Model):
name = models.CharField(max_length=100)
categories = models.ForeignKey(Category, blank=True, null=True,
on_delete=models.CASCADE)
class Meta:
verbose_name_plural = "Categories"
def __str__(self):
return self.name
views.py
def CourseListView(request):
qs = Course.objects.all()
categories = Category.objects.all()
category = request.GET.get('category')
if is_valid_queryparam(category) and category != 'All categories':
qs = qs.filter(categories__name=category)
qs = qs.filter(Q(categories__name_en='category') |
Q(categories__name_fr='category'))
context = {
'queryset': qs,
'categories': categories,
}
urls.py
path('', CourseListView, name='course-list'),
course_list.htnl
<form method="GET" action=".">
<select onchange="this.form.submit()" id="category" name="category">
<option selected>{% translate "All categories" %}</option>
{% for cat in categories %}
<option value="{{ cat }}">{{ cat }}</option>
{% endfor %}
</select>
</form>
I have tried to use this code it doesn't work,
if is_valid_queryparam(category) and category != 'All categories':
qs = qs.filter(Q(categories__name_en='category') |
Q(categories__name_fr='category'))
However this one do work but on default language only:
if is_valid_queryparam(category) and category != 'All categories':
qs = qs.filter(categories__name=category)