elMor3no
elMor3no

Reputation: 45

Django form is not valid when LANGUAGE_SESSION_KEY is not english

In my project I set the language thats the user select in the profile (englsih, spanhish, etc)

view.py

def set_idiom(request):

    from django.utils import translation
    user    = request.user

    if request.user.is_authenticated:
        user_language = user.profile.idiom
        translation.activate(user_language)
        request.session[translation.LANGUAGE_SESSION_KEY] = user_language
    else:
        user_language = 'en'
        translation.activate(user_language)
        request.session[translation.LANGUAGE_SESSION_KEY] = user_language
    print(user_language)
    return user_language

forms.py

class CreateCourse(forms.ModelForm):
    class Meta:
        model  = Courses
        fields = ('course_name', 'course_cant', 'course_description', 'course_target_lng', 'course_expert_lng', 'course_link_ptn', 'course_start', 'course_end',)
        widgets = {
            'course_name': forms.TextInput(attrs={'placeholder':u'Course name...', 'class': 'form-control'}),
            'course_cant': forms.NumberInput(attrs={'class': 'form-control'}),
            'course_description': forms.Textarea(attrs={'class': 'form-control'}),
            'course_target_lng': forms.Select(attrs={'placeholder':u'Select a target idiom', 'class': 'form-control', }),
            'course_expert_lng': forms.Select(attrs={'class': 'form-control custom-select'}),
            'course_start': forms.DateInput(attrs={'autocomplete': 'off', 'placeholder':u'Select a date', 'class': 'form-control'}),
            'course_end': forms.DateInput(attrs={'autocomplete': 'off', 'placeholder':u'Select a date', 'class': 'form-control'}),
        }  

Every time I sumit the info the form is not valid if the user select a diferent idiom as english

Upvotes: 1

Views: 515

Answers (1)

armin shoughi
armin shoughi

Reputation: 64

I think is because of not existing idom in languages code, first check it :

from django.utils.translation import check_for_language
user_language = user.profile.idiom
if user_language and check_for_language(user_language ):
    translation.activate(user_language)
else:
    raise Exeption()

django.utils.translation.check_for_language() which checks if the given language is supported by Django. read more

Upvotes: 1

Related Questions