标签:des style blog http color os io 使用 ar
1 # -*- coding:utf-8 -*- 2 from django import forms 3 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里面是models里已定义的字段
接下来是视图里的对应代码
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})
注意第一行的@,这个用于防止数据传递时出现CSRF
接下来是html里使用的方式
1 <form action=‘contact‘ method=‘post‘> 2 {% csrf_token %} 3 {{ form.project} 4 </form>
{%csrf_token%}仍然是防止出现CSRF的
“{{ }}"这个括起来的是变量,用于接收对应字段的数据,在html中显示的是一个输入框,向当于<input>,所以,前面需要配什么东西,就按照html自己添加吧
标签:des style blog http color os io 使用 ar
原文地址:http://www.cnblogs.com/ypx-blackice/p/3953151.html