ruk·si

🍡 Django Tutorial
Form Classes

Updated at 2018-11-23 18:29

Create polls/forms.py:

from django import forms


class ContactForm(forms.Form):
    name = forms.CharField()
    message = forms.CharField(widget=forms.Textarea)

    def send_email(self):
        print(self.cleaned_data)

Create polls/templates/polls/contact.html:

<form action="{% url 'polls:contact' %}" method="post">
    {% csrf_token %}
    <table>
        {{ form.as_table }}
    </table>
    <input type="submit" value="Send" />
</form>

Edit poll/view.py:

# ...

from polls.forms import ContactForm
from django.views.generic import FormView

# ...

class ContactView(generic.FormView):
    template_name = 'polls/contact.html'
    form_class = ContactForm

    def form_valid(self, form):
        form.send_email()
        return HttpResponseRedirect(self.request.path)

Edit polls/urls.py:

urlpatterns = [
    # ...
    path('contact/', views.ContactView.as_view(), name='contact'),
    # ...
]