Question

I am making a Chinese blog using django. I write everything I can control in Chinese, such as post text, blog title, blog navigation, and the label tags of the comment and contact-me forms. The only things I cannot control are the form submitting errors such as 'This field is required.', 'Enter a valid email address.'. Because I use django comment framework and form library to make my comment form and contact-me form, I don't know how to replace that English version to Chinese version.

So I resort to django internationalization. Following the django document, I add some translation strings to the forms' original html files that django provides to me, like

{% for error in field.errors %}
    <li>{% trans error %}</li>
{% endfor %}

{% for error in form.sender.errors %}
    <li>{% trans error %}</li>
{% endfor %}

Then I make message files in my project root directory and add 'django.middleware.locale.LocaleMiddleware' to the MIDDLEWARE_CLASSES setting.

In the .po file, the constant strings have record, like {% trans 'Welcome to my site' %} has the record:

msgid "Welcome to my site."
msgstr ""

But the variable content like {% trans error %} has no record.

I still go on, and reload my blog. I saw 'This field is required.' is translated to Chinese, both in the comment form and contact-me form, but 'Enter a valid email address' is still in English. I try manually adding a new record, like

msgid "Enter a valid email address."
msgstr "XXXXXXX"

to .po file, but no effect.

Why django translate some error message and ignore other error message?

If django cannot translate some string automatically or I just don't like the translation django automatically provides to me, can I provide my own translation to it? If so, where do I put the translated string, as .po file has no corresponding record?

Était-ce utile?

La solution

我觉得你需要做的是自定义表单错误提示消息。 我给有一段示例代码,你感受下。

(I think you just need to define the custom error message in the Form. like this:)

class UserForm(forms.Form):
    username = forms.EmailField(required=True, error_messages={
        'required':'your message here', 'invalid':'your message here'})
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top