Django form, data storage

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.