Django - form表单


详情:

https://docs.djangoproject.com/en/3.0/topics/forms/

两种:

  • django.forms.Form 所有表单的父类
  • django.forms.ModelForm 和模型类绑定的Form

使用Form的父类:

首先在app下创建一个forms.py的表单文件。

1
2
3
4
5
6
7
8
9
10
from django import forms

class PublisherForm(forms.Form):
name = forms.CharField(label="名称")
address = forms.CharField(label="地址")
city = forms.CharField(label="城市")
state_province = forms.CharField(label="省份")
country = forms.CharField(label="国家")
website = forms.URLField(label="网址")

在views里面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def add_pulisher(request):
if request.method == "POST":
publisher = PublisherForm(request.POST)
if publisher.is_valid():
name = publisher.cleaned_data["name"]
address = publisher.cleaned_data["address"]
city = publisher.cleaned_data["city"]
state_province = publisher.cleaned_data["state_province"]
country = publisher.cleaned_data["country"]
website = publisher.cleaned_data["website"]
Publisher.objects.create(
name=name,
address=address,
city=city,
state_province=state_province,
country=country,
website=website,
)
return HttpResponse("提交成功")
pub_form = PublisherForm()
return render(request, "blog/add.html", locals())

使用ModelForm

1
2
3
4
5
6
7
from django import forms

class PushlierModelForm(forms.ModelForm):

class Meta:
model = Publisher
exclude = ("id", )

在view中:

1
2
3
4
5
6
7
8
9
10

def add_pulisher(request):
if request.method == "POST":
publisher = PushlierModelForm(request.POST)
if publisher.is_valid():
publisher.save()
return HttpResponse("提交成功")
return redirect("/")
pub_form = PushlierModelForm()
return render(request, "blog/add.html", locals())

表单的验证:

https://docs.djangoproject.com/en/3.0/ref/forms/validation/

三种方式验证表单对象:

  • 表单字段的验证器

  • clean_filedname, 验证字段针对某个字段进行验证

  • 表单clean方法,针对整个表单进行验证