2013-03-27 64 views
1

我努力在表单中启用国际化。据我了解docs和我阅读的帖子,必须将以下设置添加到应用程序,以使表单国际化工作。启用Django表格国际化

  1. 在settings.py中将USE_L10N设置为True;鉴于USE_L10N =真
  2. 设置的地点:

    import locale 
    locale.setlocale(locale.LC_ALL, 'de_DE') 
    
  3. 对于每个表单字段组定位于正确:

    class ExpenditureForm(forms.ModelForm): 
        class Meta: 
         model = Expenditure 
         fields = ('gross_value', 'tax', 'receipt_date', 'currency', 'description', 'receipt',) 
    
    def __init__(self, *args, **kwargs): 
        super(ExpenditureForm, self).__init__(*args, **kwargs) 
        self.fields['gross_value'].localize = True 
        self.fields['gross_value'].widget.is_localized = True #added this as reaction to comments. 
    

简化的模型看起来像这样:

class Expenditure(models.Model): 
    user = models.ForeignKey(User) 
    purchase_order_membership = models.ForeignKey(PurchaseOrderMembership) 
    month = models.PositiveIntegerField(max_length=2) 
    year = models.PositiveIntegerField(max_length=4) 
    net_value = models.DecimalField(max_digits=12, decimal_places=2) 
    gross_value = models.DecimalField(max_digits=12, decimal_places=2) 

我执行了这些步骤,但是Dj ango仍然只接受带有小数点分隔符的数字输入,而不是德文记号所需的逗号作为小数点分隔符。

所以可能我错过了一个步骤。我也不确定在哪里设置区域设置。我认为这个观点不适合做这件事。对于每个请求,在视图中设置区域设置不会非常干燥。

感谢您的帮助。

+0

您是否试过激活德语'translation.activate('de_DE')'? 'https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.translation.activate(你可以从django.utils导入翻译) – danihp 2013-03-27 14:41:17

+0

感谢您的提示。我试过了,但不幸的是它没有改变任何东西。 – 2013-03-27 17:36:15

+0

另外:'self.fields ['gross_value']。widget.is_localized = True'!这个对我有用。 – danihp 2013-03-27 18:44:49

回答

2

您的表单是正确的,也是settings.py。优雅的方法是在中间件中设置翻译激活,但在视图中。见stefanw's answer的细节,我引用在这里回答:

from django.utils import translation 

class LocaleMiddleware(object): 
    """ 
    This is a very simple middleware that parses a request 
    and decides what translation object to install in the current 
    thread context. This allows pages to be dynamically 
    translated to the language the user desires (if the language 
    is available, of course). 
    """ 

    def process_request(self, request): 
     language = translation.get_language_from_request(request) 
     translation.activate(language) 
     request.LANGUAGE_CODE = translation.get_language() 

记住注册的中间件。

+0

谢谢。这是问题。语言必须在中间件中激活。在视图中激活它不起作用,并没有多大意义。 – 2013-03-27 21:03:56