How to localize Content of a Django application

后端 未结 9 1779
暖寄归人
暖寄归人 2020-12-24 09:16

Hey, i am currently working on a django app for my studies, and came to the point of l18n. Localizing the site itself was very easy, but now i have to allow users, to transl

9条回答
  •  無奈伤痛
    2020-12-24 10:08

    I have 2 languages on my site: English and Arabic Users can switch between languages clicking on a flag. In models i use a proxy model:

    class Product(models.Model):
        name=models.CharField(max_length=100)
        name_ar=models.CharField(max_length=100, default='')
    
        def __unicode__(self):
            return self.name
    
    class Product_ar(Product):
        def __unicode__(self):
            return self.name_ar
        class Meta:
            proxy=True
    

    In forms I use 2 forms instead of one:

    class CollectionEditForm_en(forms.Form):
        name = forms.CharField(label=_('Name'), max_length=100, widget=forms.TextInput(attrs={'size':'50'}))
        product = forms.ModelChoiceField(label=_('product'), queryset=Product.objects.filter(enabled=True), empty_label=None)
    
    class CollectionEditForm_ar(forms.Form):
        name = forms.CharField(label=_('Name'), max_length=100, widget=forms.TextInput(attrs={'size':'50'}))
        product = forms.ModelChoiceField(label=_('product'), queryset=Product_ar.objects.filter(enabled=True), empty_label=None)
    

    In code check language this way:

    if request.LANGUAGE_CODE=='ar':
        CollectionEditForm=CollectionEditForm_ar
    else:
        CollectionEditForm=CollectionEditForm_en
    

    So in templates i check:

    {% if LANGUAGE_CODE == "ar" %}
      {{product.name_ar}}
    {% else %}
      {{product.name}}
    {% endif %}
    

    Hope this solution will help somebody

提交回复
热议问题