Django: despite selected language, Forms still rely on LANGUAGE_CODE to format datetime (demo included)

后端 未结 1 1070
醉话见心
醉话见心 2020-12-21 23:40

I have created a small demo to show the problem.

When you click on British English, you can see how both the date- and time format change accordingly, which is grea

相关标签:
1条回答
  • 2020-12-22 00:38

    Fixed!! Hi Kave, after some time looking into your problem, finally I have found a solution.

    • First of all, you should use activate( language_code ) to switch to new language.
    • You must set as localized both: field and widget:

    Sample switch language:

    def display_current_language(request):
        if request.LANGUAGE_CODE == 'en-gb':
            lang = "You prefer to read British English {code}.".format(
                      code=request.LANGUAGE_CODE )
            activate(request.LANGUAGE_CODE)
        elif request.LANGUAGE_CODE == 'en-us':
            lang = "You prefer to read American English {code}.".format(
                      code=request.LANGUAGE_CODE )
            activate('en-us')    
        else:
            lang = "You prefer to read Deutsch {code}.".format( 
                       code=request.LANGUAGE_CODE )
            activate(request.LANGUAGE_CODE)    
        return lang
    

    Sample using your model (company) and your field ( date ):

    class CompanyForm(ModelForm):        
        class Meta:
            model = Company 
    
        def __init__(self, *args, **kwargs):
            super(CompanyForm, self).__init__(*args, **kwargs)
            self.fields['date'].localize = True
            self.fields['date'].widget.is_localized = True
    
    0 讨论(0)
提交回复
热议问题