Théo Lavaux
Théo Lavaux

Reputation: 1454

Django Model Form validation doesn't show

I needed some validation on a Django ModelForm field. So I changed 2 lines in my models.py (just below). The validation is blocking as necessary, but I can't find the proper way to display the ValidationError. Maybe there is a cleaner way to do this in the model form ?

models.py

class Lexicon(models.Model):

    [...]

    alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', _('Only alphanumeric characters are allowed'))
    filename = models.CharField(_("Filename"), max_length=40, validators=[alphanumeric])

forms.py

class LexiconForm(forms.ModelForm):
    class Meta:
        model = Lexicon
        fields = ['filename', 'language', 'comment', 'alphabet', 'case_sensitive', 'diacritics']

views.py

@login_required
def new_pls_view(request):
    if request.method == 'POST':
        form = LexiconForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user
            obj.save()
            return redirect('pls_edit')
    else:
        form = LexiconForm()
    return render(request, 'main/new_pls.html', {
        'form': form,
    })

template.html

<form class="form-horizontal" method="post" action="{% url 'new_pls' %}">
    {% csrf_token %}

{% if form.non_field_errors %}
    <div class="alert alert-danger" role="alert">
        {% for error in form.non_field_errors %}
            {{ error }}
        {% endfor %}
    </div>
{% endif %}

[...]

{% if form.is_bound %}
    {% if form.filename.errors %}
        {% for error in form.filename.errors %}
            <div class="invalid-feedback">
                {{ error }}
            </div>
        {% endfor %}
    {% endif %}

    {% if form.filename.help_text %}
        <small class="form-text text-muted">{{ form.filename.help_text }}</small>
    {% endif %}
{% endif %}

{% render_field form.filename type="text" class+="form-control" id="plsFilename" placeholder=form.filename.label %}

Replacing my entire form by {{ form }} as @Alasdair suggested is working, so I guess something is wrong with my template rendering.

Upvotes: 0

Views: 408

Answers (1)

Th&#233;o Lavaux
Th&#233;o Lavaux

Reputation: 1454

I've simply replaced my error printing by this and the error prints!

<form class="form-horizontal" method="post" action="{% url 'new_pls' %}">
    {% csrf_token %}

    {{ form.non_field_errors }}

    [...]

    {{ form.filename.errors }}
    {% render_field form.filename type="text" class+="form-control" id="plsFilename" placeholder=form.filename.label %}

Upvotes: 1

Related Questions