John Charger
John Charger

Reputation: 426

How to add an error message for an unfulfilled field in a form?

I am making a contact form. It renders fine when I let Django unpack the form’s fields with {{ form.as_p }} in my template, but If I wont to render fields manually then I have a problem.

What I want is to add a error message if a field is unfulfilled.

This is what I done using django documentation https://docs.djangoproject.com/en/1.8/topics/forms/

<form role="form" method="post">
    {% csrf_token %}
{{ form.non_field_errors }}
<div class="fieldWrapper">
    {{ form.contact_name.errors }}
    <label for="{{ form.contact_name.id_for_label }}">Name:</label>
    {{ form.contact_name }}
</div>
<div class="fieldWrapper">
    {{ form.content.errors }}
    <label for="{{ form.content.id_for_label }}">Message:</label>
    {{ form.content }}
</div>
<div class="fieldWrapper">
    {{ form.contact_email.errors }}
    <label for="{{ form.contact_email.id_for_label }}">Email:</label>
    {{ form.contact_email }}
</div>
    <input type="submit" value="Submit" />
</form>

But I don't get the error message if some field is unfulfilled. I just get an empty form defined in my view.py under else form = form_class()

This is the code I am using now:

views.py

def contact(request):
    form_class = ContactForm
    if request.method == 'POST':
        form = form_class(data=request.POST) 
        if form.is_valid():
            contact_name = request.POST.get('contact_name', '')
            contact_email = request.POST.get('contact_email', '')
            form_content = request.POST.get('content', '')

            template = get_template('agency/contact_template.txt')
            context = Context({
                'contact_name': contact_name,
                'contact_email': contact_email,
                'form_content': form_content,
            })

            content = template.render(context)

            email = EmailMessage(
                "New messages",
                content,
                "My web site " + '<[email protected]>',
                ['[email protected]'],
                headers = {'Message respond to': contact_email}
            )    
            email.send()

            return render_to_response('papers/thank_you.html', {}, context_instance=RequestContext(request))

        else:
            form = form_class()

    return render_to_response('papers/contact.html', {'form': form_class}, context_instance=RequestContext(request))

contact.html

        <form role="form" id="contact-form"  action="" method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <p class="contact-submit">
                <button id="contact-submit" class="submit" type="submit" value="Submit">Send</button>
            </p>
        </form>

forms.py

from django import forms

class ContactForm(forms.Form):
    contact_name = forms.CharField(required=True)
    contact_email = forms.EmailField(required=True,)
    content = forms.CharField(
        required=True,
        widget=forms.Textarea)


    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        self.fields['contact_name'].label = "Name:"
        self.fields['contact_email'].label = "Email:"
        self.fields['content'].label = "Message"

Upvotes: 2

Views: 108

Answers (1)

Alasdair
Alasdair

Reputation: 309009

Your indentation is incorrect. The else block should be in line with the if request.method == POST.

if request.method == 'POST':
    form = form_class(data=request.POST) 
    if form.is_valid():
       # process form and return response
else:
    form = form_class()

This way, the bound form with the post data is used when the form is invalid, and any errors will be displayed to the user. Since you have required=True, Django will automatically add an error if a required field is left blank.

Secondly, when you render your template, you need to pass the form, not the form class.

return render_to_response('papers/contact.html', {'form': form}, context_instance=RequestContext(request))

Finally, it's a good idea to redirect to a 'thank you' page after sending the email, instead of rendering the 'thank you' template. This stops multiple emails being sent if the user refreshes the thank you page.

Upvotes: 1

Related Questions