Django version 1.4.5 used
1 # -*- coding:utf-8 -*-2 from django import forms3 4 class ContactForm(forms.Form):5 project = forms.CharField(max_length=30)6 subject = forms.CharField(max_length=20)7 name = forms.CharField(max_length=20, error_messages={‘required‘: ‘Please enter your name‘})8 describ = forms.CharField(max_length=200,widget=forms.Textarea({‘style‘:‘width:240px; height: 125px‘}))
Form. py
In form, it is a field defined in models.
Next is the corresponding code in the view.
1 @csrf_protect 2 def contact(request): 3 advice = Advice.objects.all().order_by(‘-adv_date‘) 4 if request.method == ‘POST‘: 5 form = ContactForm(request.POST) 6 if form.is_valid(): 7 project = form.cleaned_data[‘project‘] 8 subject = form.cleaned_data[‘subject‘] 9 name = form.cleaned_data[‘name‘]10 describ = form.cleaned_data[‘describ‘]11 12 Advice.objects.create(project=project, subject=subject, name=name, describ=describ)13 return HttpResponse(‘Thanks !‘)14 else:15 form = ContactForm()16 return render(request, ‘contact.html‘,{‘form‘:form,‘advice‘:advice})
Views. py
Note the @ In the first line, which is used to prevent csrf from occurring during data transmission.
The following is the method used in HTML.
1 <form action=‘contact‘ method=‘post‘>2 {% csrf_token %}3 {{ form.project}4 </form>
View code
{% Csrf_token %} still prevents csrf
"{{}}" Is a variable that is used to receive data from the corresponding field. In HTML, an input box is displayed, directed to <input>. Therefore, add your own items according to HTML.
Django form, data storage