from django import forms
2. 在forms.py文件中新建表单模型
class BlogForm(forms.Form):
name=forms.CharField(max_length=128)
3. 在函数中返回表单
def blog(request):
form = BlogForm()
return render_to_response("blog.html",{"form":form})
4. 页面展示表单
<body>
{{ form }}
</body>
5. 页面POST提交表单到view中处理
view中相关代码,使用post方式时注意需要添加:
context_instance=RequestContext(request)
from django.template import RequestContext
def blog(request):
if request.method == 'POST': # 如果表单被提交
form = BlogForm(request.POST)
if form.is_valid(): # 验证表单
print("input name="+form.name)
form.name="successful"
return render_to_response("blog.html",{"form":form},context_instance=RequestContext(request))
form = BlogForm()
return render_to_response("blog.html",{"form":form},context_instance=RequestContext(request))
html相关代码
<form action="/blog/" method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" value="提交"/>
</form>