Django-表单使用
-----表单使用
1、定义表单类
1-1、
<form action="" method="post">
<input type="text" name="title">
<input type="date" name="pub_date">
<input type="submit">
</form>
1-2、 新建一个forms.py文件,编写Form类。
from django import forms
class BookForm(forms.Form):
title = forms.CharField(label="书名", required=True, max_length=50)
pub_date = forms.DateField(label='出版日期', required=True)
2、视图中使用表单类
from django.shortcuts import render
from django.views.generic import View
from django.http import HttpResponse
from .forms import BookForm
class BookView(View):
def get(self, request):
form = BookForm()
return render(request, 'book.html', {'form': form})
def post(self, request):
form = BookForm(request.POST)
if form.is_valid(): # 验证表单数据
print(form.cleaned_data) # 获取验证后的表单数据
return HttpResponse("OK")
else:
return render(request, 'book.html', {'form': form})
3、模板中使用表单类
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>书籍</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit">
</form>
</body>
</html>
4、模型类表单
class BookForm(forms.ModelForm):
class Meta:
model = BookInfo
fields = ('btitle', 'bpub_date')