lucky3
lucky3

Reputation: 53

Django does not translate filter labels

I am using django-filters for filtering on my site and the filter labels are being translated correctly on every page except two. I have checked all the common problems like making sure il8n is loaded to both pages, testing the path to the locale folder, restarting the server, checking middleware & other settings, checking for fuzzy tags in translations file, etc. The only similarity I can think of between them is that they both use Django's built-in Paginator when none of the other pages on the site do. Would that be enough to break translation? I am including the code for one of the two pages in the hopes that someone can tell me what's going on. If anyone wants to see other pieces of the code the github is here

models_FSJUser.py

class FSJUser(models.Model):
    # List the languages a user may choose from in human readable format and also make them accessible in other files 
    # via FSJUser.LANG_CHOICES, FSJUser.ENGLISH, etc.
    FRENCH = 'fr'
    ENGLISH = 'en'
    LANG_CHOICES = (
        (FRENCH, "Fran"+u"\u00E7"+"ais"),
        (ENGLISH, 'English'),
    )   
    # Link FSJUser with a User model for authentication related business
    user = models.OneToOneField(User, on_delete = models.CASCADE, blank = True, null = True)    

    # All FSJ Users have these attributes in common
    ccid = models.CharField(max_length = 255, unique = True, verbose_name = _("CCID"))
    first_name = models.CharField(max_length = 255, verbose_name = _("First Name"))
    last_name = models.CharField(max_length = 255, verbose_name = _("Last Name"))
    email = models.EmailField(max_length = 254, verbose_name= _("Email"))
    lang_pref = models.CharField(max_length = 2, blank = False, choices = LANG_CHOICES, default = FRENCH, verbose_name = _("Language Preference"))

models_student.py

# This class inherits from a standard FSJ User and extends for Student specific attributes and methods
class Student(FSJUser):
    program = models.ForeignKey(Program, on_delete = models.SET_NULL, null = True, blank = True, verbose_name = _("Program"))
    year = models.ForeignKey(YearOfStudy, on_delete=models.PROTECT, verbose_name = _("Year"))
    gpa = models.CharField(max_length = 10, null = True, blank = True, verbose_name = _("GPA"))
    middle_name = models.CharField(max_length = 50, blank = True, verbose_name = _("Middle Name"))
    student_id = models.CharField(max_length = 10, unique = True, verbose_name = _("U of A Student ID"), validators=[validate_student_id])    

filters.py

from .models import *
import django_filters
from django.forms import CheckboxSelectMultiple, DateInput
from django.utils.translation import gettext_lazy as _

LOOKUP_TYPES = [
        ('icontains', _("contains"))
]

class StudentFilter(django_filters.FilterSet):
    ccid = django_filters.CharFilter(lookup_expr='icontains')
    first_name = django_filters.CharFilter(lookup_expr='icontains')
    middle_name = django_filters.CharFilter(lookup_expr='icontains')
    last_name = django_filters.CharFilter(lookup_expr='icontains')
    student_id = django_filters.CharFilter(lookup_expr='icontains')
    class Meta:
        model = Student
        fields = ['ccid','first_name','middle_name','last_name','student_id','year','program']

views.py

def coordinator_students(request):
    FSJ_user = get_FSJ_user(request.user.username)
    student_list = Student.objects.all().order_by('ccid')
    filtered_list = StudentFilter(request.GET, queryset=student_list)

    student_paginator = Paginator(filtered_list.qs, 25)

    template = loader.get_template("FSJ/coord_student_list.html")
    context = get_standard_context(FSJ_user)
    context["student_list"] = student_list

    page = request.GET.get('page', 1)

    try:
        students = student_paginator.page(page)
    except PageNotAnInteger:
        students = student_paginator.page(1)
    except EmptyPage:
        students = student_paginator.page(student_paginator.num_pages)

    context["filter"] = filtered_list
    context["students"] = students
    return HttpResponse(template.render(context, request))

Upvotes: 0

Views: 527

Answers (1)

lucky3
lucky3

Reputation: 53

I've solved this problem, but I'm going to post the answer here in case anyone else runs into this same issue.

I did not figure out the root of the problem (although I now suspect it is because I defined custom filters instead of letting them be autogenerated); however the solution that I found worked best was to define the labels for each filter separately in the filter's init function, like so:

    def __init__(self, *args, **kwargs):
        super(StudentFilter, self).__init__(*args, **kwargs)

        # Adding custom translatable labels to autogenerated filters
        self.filters['year'].label = _("Year:")

Hope this helps someone.

Upvotes: 1

Related Questions