I wrote this contact form with some help from the Django docs:
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_data['cc_myself']
recipients = ['[email protected]']
if cc_myself:
recipients.append(sender)
m = '%s\n\n-----------------\n%s' % (message, name)
from django.core.mail import send_mail
send_mail(subject, m, sender, recipients)
return HttpResponseRedirect('/kontakt/tack/')
else:
form = ContactForm()
return render(request, 'contact/index.html', {
'form': form,
})
The problem is that if the form doesn't validate it returns an empty form. That could be a big annoyance for someone that have written a long message but forgot to put his name in or something.
I've fixed that by change the the code below to last else: to:
try:
form = ContactForm(form.cleaned_data)
except UnboundLocalError:
form = ContactForm()
I needed to try-statement for the first rendering of the page when no form.cleaned_data yet exist. This works, but it seems like a rather ugly hack.
Is there some standard way to use the text from previous fill in when re-rendering the form without my ugly try-except solution?
Template on request
{% block content %}
<div id="contact-generic-container">
<p>Lorem ipsum (not really, but ain't relevant).</p>
</div> <!-- #contact-generic-container -->
<div id="contact-form" class="clearfix">
<br/>
<h2>Kontakta oss!</h2>
<form action="/kontakt/" method="post">
{{ form.non_field_errors }}
<fieldset class="text">
{% csrf_token %}
<div class="field-wrapper">
<label for="id_name">Namn:</label>
{{ form.name }}
{{ form.name.errors }}
</div>
<div class="field-wrapper">
<label for="id_sender">E-post:</label>
{{ form.sender }}
{{ form.sender.errors }}
</div>
<div class="field-wrapper">
<label for="id_subject">Ämne:</label>
{{ form.subject }}
{{ form.subject.errors }}
</div>
</fieldset>
<fieldset class="text">
<div class="field-wrapper">
<label for="id_message">Meddelande:</label><br/>
{{ form.message }}
{{ form.message.errors }}
</div>
<div class="field-wrapper">
<label for="id_cc_myself">Kopia till mig själv:</label>
{{ form.cc_myself }}
{{ form.cc_myself.errors }}
</div>
<input type="submit" value="Skicka" />
<fieldset class="text">
</form>
</div>
{% endblock %}
elseis lined up with the firstif? Have you checked tabs/spaces?