標籤:des style blog http color os io 使用 ar
使用的django版本 1.4.5
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
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})views.py
注意第一行的@,這個用於防止資料傳遞時出現CSRF
接下來是html裡使用的方式
1 <form action=‘contact‘ method=‘post‘>2 {% csrf_token %}3 {{ form.project}4 </form>View Code
{%csrf_token%}仍然是防止出現CSRF的
“{{ }}"這個括起來的是變數,用於接收對應欄位的資料,在html中顯示的是一個輸入框,向當於<input>,所以,前面需要配什麼東西,就按照html自己添加吧
django的form,資料存入方面