changing the field name django uses when display form error messages

久未见 提交于 2019-12-11 02:54:58

问题


Okay so I have a form and then in the template, I have this code:

{% if form.errors %}
    { form.errors %}
{% endif %}

Now, suppose I have a username field in my form which is required and I purposely do not fill it out. It would say

username
    -This field is required

How do I change the word "username" which it displays when telling what field the error message is for? I'm guessing it is taking the name from the Model I created because in the model (which I then made a form of) I had written

username = models.CharField(max_length=10)
first_name = models.CharField(max_length=20)

As you can see, if there is an error with the first_name field, it django would display

first_name
    - *error message*

How would I make it display "First Name" instead of "first_name"?


回答1:


If you want to put some custom messages to your erros you may want to modify the clean method of your formfields.

For example:

class Form(forms.ModelForm):
    class Meta:
        model = User #Assuming User is the name of your model
        fields = ['username','first_name']

    def clean_first_name(self):
        if condition: # A condition that must raise an error
            raise forms.ValidationError(u'Your Custom Validation Error goes here.')
        return self.cleaned_data['first_name']

But if you just want to change the name that appears in a default error message you can put a verbose name in your fields, just like:

username = models.CharField(max_length=10, verbose_name="Username")
first_name = models.CharField(max_length=20, verbose_name="First Name")

or implicit:

username = models.CharField("Username", max_length=10)
first_name = models.CharField("First Name",max_length=20)

To see more about django form and field validation: https://docs.djangoproject.com/en/1.5/ref/forms/validation/#form-and-field-validation

About Override default Form error messages: Django override default form error messages

and

http://davedash.com/2008/11/28/custom-error-messages-for-django-forms/



来源:https://stackoverflow.com/questions/18995034/changing-the-field-name-django-uses-when-display-form-error-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!