[Fixed]-Django Forms errors using action parameter

1👍

You are creating a new form when the form is not valid. The new form contains no data for the current request so of course will not have any errors.

Try this:

if request.POST:
    mailform = Mail(request.POST)
    if mailform.is_valid():
        mail = mailform.cleaned_data['email']
        message = "Email: " + mail
        send_mail(...)
        return HttpResponseRedirect('/callbackresult/')
    else:
        return render(request, 'template.html', {'mailform':mailform})
else:
    mailform = Mail()
    return render(request, 'template.html', {'mailform':mailform})

Its also better to use render() when returning the form with errors since you are not actually redirecting the user to a different page

0👍

I used this way to display error in the frontend. When error you need to pass the form object into template.

mailroom = Mail(request.POST)
if mailroom.is_valid():
    # save here.
else:
    return render(request, 'main/index.html', {'mailroom': mailroom})

and in template {{ mailform.errors }} will give you the errors.

0👍

django.contrib provide message to these problems.

from django.contrib import messages
# then in your form view, take callback form for example
callbackform = CallBackForm(request.POST)
    if callbackform.is_valid():
        messages.success(request,"success")
    else:
        messages.error(request,"error")
# and in the template
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}

by default, django.contrib.messages is in your ‘INSTALLED_APPS’, if not, you need to check it.

Leave a comment