1from django import forms
2
3# creating a form
4class SampleForm(forms.Form):
5 name = forms.CharField()
6 description = forms.CharField()
1if form.is_valid():
2 post = form.save(commit=False)
3 post.author = request.user
4 post.published_date = timezone.now()
5 post.save()
6
1# application/forms.py
2
3from django import forms
4
5class ContactForm(forms.Form):
6 name = forms.CharField(max_length=100)
7 email = forms.EmailField()
8 message = forms.CharField(max_length=1000)
9
1class YourForm(ModelForm):
2 class Meta:
3 model = YourModel
4 fields = ['pub_date', 'headline', 'content', 'reporter']
1{% extends 'base.html' %}
2
3{% block content %}
4 <h2>Sign up</h2>
5 <form method="post">
6 {% csrf_token %}
7 {% for field in form %}
8 <p>
9 {{ field.label_tag }}<br>
10 {{ field }}
11 {% if field.help_text %}
12 <small style="color: grey">{{ field.help_text }}</small>
13 {% endif %}
14 {% for error in field.errors %}
15 <p style="color: red">{{ error }}</p>
16 {% endfor %}
17 </p>
18 {% endfor %}
19 <button type="submit">Sign up</button>
20 </form>
21{% endblock %}
1from django.http import HttpResponseRedirect
2from django.shortcuts import render
3
4from .forms import NameForm
5
6def get_name(request):
7 # if this is a POST request we need to process the form data
8 if request.method == 'POST':
9 # create a form instance and populate it with data from the request:
10 form = NameForm(request.POST)
11 # check whether it's valid:
12 if form.is_valid():
13 # process the data in form.cleaned_data as required
14 # ...
15 # redirect to a new URL:
16 return HttpResponseRedirect('/thanks/')
17
18 # if a GET (or any other method) we'll create a blank form
19 else:
20 form = NameForm()
21
22 return render(request, 'name.html', {'form': form})
23