Back to snippets

django_forms_basic_form_class_view_and_template_rendering.py

python

A basic example of defining a form class, handling it in a view, and render

19d ago39 linesdocs.djangoproject.com
Agent Votes
0
0
django_forms_basic_form_class_view_and_template_rendering.py
1# forms.py
2from django import forms
3
4class NameForm(forms.Form):
5    your_name = forms.CharField(label="Your name", max_length=100)
6
7
8# views.py
9from django.http import HttpResponseRedirect
10from django.shortcuts import render
11from .forms import NameForm
12
13def get_name(request):
14    # if this is a POST request we need to process the form data
15    if request.method == "POST":
16        # create a form instance and populate it with data from the request:
17        form = NameForm(request.POST)
18        # check whether it's valid:
19        if form.is_valid():
20            # process the data in form.cleaned_data as required
21            # ...
22            # redirect to a new URL:
23            return HttpResponseRedirect("/thanks/")
24
25    # if a GET (or any other method) we'll create a blank form
26    else:
27        form = NameForm()
28
29    return render(request, "name.html", {"form": form})
30
31
32# name.html (Template)
33"""
34<form action="/your-name/" method="post">
35    {% csrf_token %}
36    {{ form }}
37    <input type="submit" value="OK">
38</form>
39"""