1

フォームでの国際化を可能にするのに苦労しています。私が読んだドキュメントと投稿を理解している限り、フォームの国際化を機能させるには、アプリに次の設定を追加する必要があります。

  1. settings.pyでUSE_L10NをTrueに設定します。USE_L10N = True
  2. ビューでロケールを設定します。

    import locale
    locale.setlocale(locale.LC_ALL, 'de_DE')
    
  3. フォームフィールドセットごとに、ローカライズを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

あなたのフォームも正しいsettings.pyです。エレガントな方法は、ミドルウェアで翻訳をアクティブ化することですが、ビュー内にあります。詳細については、 stefanwの回答を参照してください。ここで回答を引用します。

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

ミドルウェアを登録することを忘れないでください。

于 2013-03-27T20:16:57.850 に答える