1

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

  1. 在 settings.py 中将 USE_L10N 设置为 True;USE_L10N = 真
  2. 在视图中设置语言环境:

    import locale
    locale.setlocale(locale.LC_ALL, 'de_DE')
    
  3. 对于将 localize 设置为 True 的每个表单字段:

    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)

我执行了这些步骤,但 Django 仍然只接受带有点作为小数分隔符的数字输入,而不是根据德语符号的需要,将逗号作为小数分隔符。

所以可能我错过了一步。我也不确定在哪里设置语言环境。我认为视图不是合适的地方。在视图中为每个请求设置语言环境不是很干。

谢谢你的帮助。

4

1 回答 1

4

Your form is right, also settings.py . Elegant way is to set translation activate in a middleware, but in view. See stefanw's answer for details, I quote answer here:

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()

Remember to register the middleware.

于 2013-03-27T20:16:57.850 回答