I can’t figure out why validation doesn’t work in my app.
My problem is that every time I send the form in my template (base_contact.html), the app sends me to the /Thanks/ view, but it’s so weird, because it does even if the form in the template is empty or has several validation errors. So I think that form.is_valid() is not working properly in this case. These are my files:
models.py
from django.db import models
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea())
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
views.py
from django.shortcuts import render_to_response
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
from main.models import ContactForm
from django.core.mail import send_mail
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_data['cc_myself']
recipients = ['example@gmail.com']
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect('/Thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render_to_response('base_contact.html', {'form': form})
base_contact.html
<div class="forms">
<table>
<form action="/Contact/" method="post">{% csrf_token %}
<tr><th><label for="id_sender">Your email:</label></th>
<td><input class="text" type="text" name="sender" id="id_sender" /></td></tr>
<tr><th><label for="id_subject">Subject:</label></th>
<td><input class="text" id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
<tr><th><label for="id_message">Message:</label></th>
<td><textarea class="styletextarea" name="message" id="id_message" rows="7" cols="35" /></textarea></td></tr>
<tr><td></td><td><input class="button" type="submit" value="Send" /></td></tr>
</form>
</table>
</div>
Thanks for your help 🙂
Check the indentation of the following line
In Python (and therefore Django), indentation is very important. It is recommended to use 4 spaces per indentation level. Avoid using tabs. You can often change the settings for your text editor or ide to use 4 spaces when you press the tab key.