R0LL
R0LL

Reputation: 73

Django Contact Form using ModelForm

I am trying to create a contact form that will both email and store the message. I think I got the model.py, forms.py and admin.py right, and I am able to create and store (not email) a message from the admin. But I am struggling with the view.py that has to both email and store the message.

model.py:

from django.db import models
from django.contrib import admin

class Contact(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    message = models.TextField(max_length=10) 
    date_created = models.DateField(verbose_name="Created on date", auto_now_add="True")

class ContactAdmin(admin.ModelAdmin):
    list_display = ('name', 'email', 'message', 'date_created')

forms.py:

from django import forms
from .models import Contact


class ContactForm(forms.Form):
    name = forms.CharField()
    email = forms.EmailField()

When it comes to the views.py, I need some guidance in order to put together the code for the def contact(request):. I think I will have to include these modules:

from django.conf import settings
from django.shortcuts import render, HttpResponseRedirect, HttpResponse, Http404
from django.core.mail import send_mail
from .forms import ContactForm
from .models import Contact

When it comes to the template part, I am not sure on how to use the template tags to render the contact form in html.

So, I need help to figure out the correct view and template code.. I am of course open to suggestions for the rest of the code as well - As you might guessed, this is my first real Django app.

Thank you!

Upvotes: 2

Views: 1915

Answers (1)

mishbah
mishbah

Reputation: 5607

Something like this:


I would use a django ModelForm to generate the form:

class ContactForm(forms.ModelForm):

    class Meta:
        model = Contact
        exclude = ('date_created', )

Docs: https://docs.djangoproject.com/en/1.7/topics/forms/modelforms/#modelform

And FormView for the actual view:

from django.conf import settings
from django.core.mail import send_mail
from django.views.generic import FormView

from .forms import ContactForm

class ContactFormView(FormView):

    form_class = ContactForm
    template_name = "email_form.html"
    success_url = '/email-sent/'

    def form_valid(self, form):
        message = "{name} / {email} said: ".format(
            name=form.cleaned_data.get('name'),
            email=form.cleaned_data.get('email'))
        message += "\n\n{0}".format(form.cleaned_data.get('message'))
        send_mail(
            subject=form.cleaned_data.get('subject').strip(),
            message=message,
            from_email='[email protected]',
            recipient_list=[settings.LIST_OF_EMAIL_RECIPIENTS],
        )
        form.save()
        return super(ContactFormView, self).form_valid(form)

Docs: https://docs.djangoproject.com/en/1.7/ref/class-based-views/generic-editing/#formview

And your template:

{% extends 'base.html' %}
{% block title %}Send an email{% endblock %}

{% block content %}
    <div class="row">
        <div class="span6">
            <h1>Send an email</h1>
            <form action="." method="post">
                {% csrf_token %}
                {{ form }}
                <input type="submit" value="Submit" />
            </form>
        </div>
    </div>
{% endblock %}

{% block extrajs %}
<script src="{{ STATIC_URL }}js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function() {
    $('#id_name').focus()
});
</script>
{% endblock %}

Docs: https://docs.djangoproject.com/en/1.7/topics/forms/#the-template

Upvotes: 2

Related Questions