Question

So I have a model called Users and it has a field called first_name.

class Users(models.Model):
    alpha_field = RegexValidator(regex=r'^[a-zA-Z]+$', message='Name can only contain letters')
    user_id = models.AutoField(unique=True, primary_key=True)
    username = models.SlugField(max_length=50, unique=True)
    first_name = models.CharField(max_length=50, verbose_name='first Name', validators=[alpha_field])
    last_name = models.CharField(max_length=50, validators=[alpha_field])
    password = models.SlugField(max_length=50)

and then I created a UsersForm and then in my template page, when displaying any error messages, it doesn't use the verbose name, it uses first_name. For example, my template code for display errors is

{% for field, error in form.errors.items %}
    {% if forloop.counter == 1 %}
        {{ field }}{{ error | striptags }}
    {% endif %}
{% endfor %}

If there is an error in the first_name field, like if I didn't fill it out and still clicked submit, it would display this

"first_nameThis field is required" How do I make it display "First NameThis field is required" instead?

Not that it might make a different but do note that I am using south and schemamigration to update the database, it originally did not have a verbose name but I recently added it and then just saved the file (I didn't do a schemamigration and then migrate the app because it said that no changes seem to have been made).

My UsersForm is this:

from django import forms
from models import Users

class UsersForm(forms.ModelForm):

    class Meta:
        model = Users
        widgets = {'password':forms.PasswordInput()}

    def __init__(self, *args, **kwargs):
        super( UsersForm, self ).__init__(*args, **kwargs)
        self.fields[ 'username' ].widget.attrs[ 'placeholder' ]="Username"
        self.fields[ 'first_name' ].widget.attrs[ 'placeholder' ]="First Name"  
        self.fields[ 'last_name' ].widget.attrs[ 'placeholder' ]="Last Name"
        self.fields[ 'password' ].widget.attrs[ 'placeholder' ]="Password"
        self.fields['first_name'].label='first Name'

my view is here:

def home_page(request):
    form = UsersForm()
    if request.method == "POST":
        form = UsersForm(request.POST)

        if form.is_valid():
            form.save()
    c = {}
    c.update(csrf(request))
    c.update({'form':form})
    return render_to_response('home_page.html', c)
Was it helpful?

Solution

form.errors is a dictionary of field NAMES as the keys and error messages as the values. It will not be the verbose_name. You need to get the field from the form, then do field.label for the verbose_name. If you use this snippet for getting an attribute on an object dynamically in a template: https://snipt.net/Fotinakis/django-template-tag-for-dynamic-attribute-lookups/, you can do something like this to get the verbose_name:

{% load getattribute %}

{% for field, error in form.errors.items %}
    {% if forloop.counter == 1 %}
        {% with field_obj=form|getattribute:field %}
            {{ field_obj.label }}{{ error | striptags }}
        {% endwith %}
    {% endif %}
{% endfor %}

OTHER TIPS

I had similar problem some time ago, this snippet helped me out:

from django import template
from django import forms
from django.forms.forms import NON_FIELD_ERRORS
from django.forms.util import ErrorDict

register = template.Library()

@register.filter
def nice_errors(form, non_field_msg='General form errors'):
    nice_errors = ErrorDict()
    if isinstance(form, forms.BaseForm):
        for field, errors in form.errors.items():
            if field == NON_FIELD_ERRORS:
                key = non_field_msg
            else:
                key = form.fields[field].label
            nice_errors[key] = errors
    return nice_errors

http://djangosnippets.org/snippets/1764/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top