Tying form objects into views

Our contact form is not much good to us unless we have some way of displaying it to the user. To do this, we need to first update our mysite/views:

# views.py 
 
from django.shortcuts import render 
from mysite.forms import ContactForm 
from django.http import HttpResponseRedirect 
from django.core.mail import send_mail 
 
# ... 
 
def contact(request): 
    if request.method == 'POST': 
        form = ContactForm(request.POST) 
        if form.is_valid(): 
            cd = form.cleaned_data 
            send_mail( 
                cd['subject'], 
                cd['message'], 
                cd.get('email', 'noreply@example.com'), 
                ['siteowner@example.com'], 
            ) 
            return HttpResponseRedirect('/contact/thanks/') 
    else: 
        form = ContactForm() 
    return render(request, 'contact_form.html', {'form': form}) 

Next, we have to create our contact ...

Get Mastering Django: Core now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.