Django最强大的部分之一是自动管理界面。它从模型中读取元数据,以提供一个快速的,以模型为中心的界面,受信任的用户可以在其中管理您网站上的内容。管理员的建议用法仅限于组织的内部管理工具。它并非旨在构建您的整个前端。
实现单项选择框
<form action="/index/" method="post">
选择A:
<select name="tag_select_a">
{% for item in total_a %}
<option value = "{{ item }}"> {{ item }} </option>
{% endfor %}
</select>
选择B:
<select name="tag_select_b">
{% for item in total_b %}
<option value = "{{ item }}"> {{ item }} </option>
{% endfor %}
</select>
<input type="submit" value="提交选择">
</form>
def index(request):
if request.method == "GET":
tag_select_a = ["HTML", "CSS", "JAVASCRIPT", "Python", "JQuery"]
tag_select_b = ["MySQL","Oracle","MSSQL"]
return render(request, "index.html", {"total_a": tag_select_a,"total_b": tag_select_b})
elif request.method == "POST":
select_a = request.POST.get("tag_select_a")
select_b = request.POST.get("tag_select_b")
return HttpResponse("选择A: {} 选择B: {}".format(select_a,select_b))<b>普通Form表单的提交</b>
提交账号密码
<!-- name:index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/" method="post">
<p>账号:<input type="text" name="username"><span>{{ error.username }}</span></p>
<p>密码:<input type="password" name="password"><span>{{ error.password }}</span></p>
<input type="submit" value="提交请求">
</form>
</body>
</html>
# name: views.py
from django.shortcuts import render,HttpResponse
def index(request):
if request.method == "GET":
return render(request,"index.html")
else:
username = request.POST.get("username")
password = request.POST.get("password")
error = {"username":"","password":""}
if len(username) > 10:
error["username"]="用户名不能大于10"
if len(password) < 5:
error["password"] = "密码不能小于5"
return render(request,"index.html",{"error":error})
Form实现登录表单
<!--name:index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/" method="post" novalidate>
<p>账号: {{ form.username }} {{ form.username.errors.0 }}</p>
<p>密码: {{ form.password }} {{ form.errors.password }}</p>
<p>重复: {{ form.RepeatPass }} {{ form.errors.RepeatPass }}</p>
<input type="submit" value="提交">
</form>
</body>
</html>
# name:views.py
from django.shortcuts import render,HttpResponse
from django.forms import Form,fields,widgets
from django.core.exceptions import ValidationError
class LoginForm(Form):
username = fields.CharField(
required = True,
max_length = 10,
error_messages={"required":"该字段不能为空"},
widget=widgets.TextInput(attrs={"placeholder":"请输入用户名","class":"form-control"})
)
password = fields.CharField(
required = True,
max_length=10,
error_messages={"required":"密码字段不能为空","min_length":"密码最小长度为5"},
widget=widgets.PasswordInput(attrs={"placeholder":"请输入密码","class":"form-control"})
)
RepeatPass = fields.CharField(
required=True,
max_length=10,
error_messages={"required":"密码字段不能为空","min_length":"密码最小长度为5"},
widget=widgets.PasswordInput(attrs={"placeholder":"重复输入密码","class":"form-control"})
)
# 自定义方法(局部钩子)密码必须包含字母和数字
def clean_password(self):
if self.cleaned_data.get("password").isdigit() or self.cleaned_data.get("password").isalpha():
raise ValidationError("密码必须包含数字和字母")
else:
return self.cleaned_data["password"]
# 自定义方法(全局钩子, 检验两个字段),检验两次密码是否一致
def clean_RepeatPass(self):
if self.cleaned_data.get("password") != self.cleaned_data.get("RepeatPass"):
raise ValidationError("两次输入密码不正确")
else:
return self.cleaned_data
def index(request):
if request.method =="GET":
form = LoginForm()
return render(request, "index.html", {"form": form})
else:
form = LoginForm(request.POST)
if form.is_valid():
# username = form.data['username']
data = form.cleaned_data
username = data.get("username")
password = data.get("password")
print(username,password)
return render(request, "index.html", {"form": form})
return render(request, "index.html", {"form": form})
Form实现用户注册
<!--name: index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<form action="/" method="post">
<p>{{ form.username.label }} {{ form.username }}</p>
<p>{{ form.password.label }} {{ form.password }}</p>
<p>{{ form.mobile.label }} {{ form.mobile }} </p>
<p>{{ form.email.label }} {{ form.email }} </p>
<p>{{ form.text }} </p>
<p><input type="submit" value="提交请求"></p>
</form>
</div>
</body>
</html>
# name: models.py
from django.db import models
class User(models.Model):
id = models.AutoField(primary_key=True)
username = models.CharField(max_length=64)
password = models.CharField(max_length=32)
mobile = models.CharField(max_length=32)
email = models.EmailField(max_length=64)
text = models.CharField(max_length=128)
# name: views.py
from django.shortcuts import render,HttpResponse
from MyWeb import models
from django.forms import Form,fields,widgets
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
class UserForm(Form):
username = fields.CharField(
label = "账号: ", # 给表单加一个标签
required = True, # 不允许字段为空值
min_length=4, # 设置最小长度
max_length = 10, # 设置最大长度
validators=[ RegexValidator(r'^[0-9a-zA-Z]+$',"用户账号只能使用,0-9a-z") ],
error_messages={"required":"该字段不能为空","invalid":"无效的用户名",
"min_length":"最小长度为5","max_length":"最大长度为10"},
widget=widgets.TextInput(attrs={"placeholder":"请输入用户名","class":"form-control"})
)
password = fields.CharField(
label = "密码: ",
required = True,
min_length=5,
max_length=10,
error_messages={"required":"密码字段不能为空","min_length":"密码最小长度为5"},
widget=widgets.PasswordInput(attrs={"placeholder":"请输入密码","class":"form-control"})
)
mobile = fields.CharField(
label = "手机: ",
required=True,
validators=[RegexValidator('[0-9]', "手机号必须是数字")],
error_messages={"required":"该字段不能为空"},
widget=widgets.TextInput(attrs={"placeholder": "手机号","class": "form-control"})
)
email = fields.EmailField(
label="邮箱: ",
required=True,
error_messages={"required":"邮箱不能为空!!","invalid":"无效的邮箱"},
widget=widgets.EmailInput(attrs={"placeholder": "邮箱", "class": "form-control"})
)
text = fields.CharField(
required=True,
widget=widgets.Textarea(attrs={"placeholder": "畅言,欢迎留言...", "class": "form-control",
"style":"margin: 0px; 203px; height: 98px;"})
)
def index(request):
if request.method =="GET":
form = UserForm()
return render(request, "index.html", {"form": form})
else:
form = UserForm(request.POST)
if form.is_valid():
# username = form.data['username']
data = form.cleaned_data
username = data.get("username")
is_exits = models.User.objects.filter(username="admin").count()
if is_exits != 0:
return HttpResponse("您注册的用户已存在")
else:
models.User.objects.create(**data)
return HttpResponse("恭喜您的账号注册完成了")
else:
return render(request, "index.html", {"form": form.errors})
return render(request, "index.html", {"form": form})
其他常用Form表单
<!--name: index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/" method="post">
{% for field in form %}
<p>{{ field.label_tag }} {{ field }} {{ field.errors.0 }}</p>
{% endfor %}
<input type="submit" value="提交" />
</form>
</body>
</html>
# name: views.py
from django.shortcuts import render,HttpResponse
from django.forms import Form,fields,widgets
class MyForm(Form):
hobby = fields.ChoiceField(
label="单选框:",
required=True,
initial=1, # 默认选择1号
choices=( (1,"篮球"),(2,"足球"),(3,"乒乓球"),(4,"滚球")),
widget=widgets.RadioSelect()
)
select = fields.ChoiceField(
label="单选框(默认):",
required=True,
initial=1,
choices=( (1,"篮球"),(2,"足球"),(3,"乒乓球"),(4,"滚球")),
widget=widgets.Select()
)
multiple = fields.MultipleChoiceField(
label="复选框",
choices=((1, "篮球"), (2, "足球"), (3, "羽毛球"), (4, "排球")),
initial=[2, 4],
widget=widgets.SelectMultiple()
)
checkbox = fields.ChoiceField(
label="单项复选框",
initial="checked", # 默认为勾选
widget=widgets.CheckboxInput()
)
multselect = fields.MultipleChoiceField(
label="多项复选框",
choices=((1, "篮球"), (2, "足球"), (3, "羽毛球"), (4, "排球")),
initial=[1, 3],
widget=widgets.CheckboxSelectMultiple()
)
data = fields.DateField(
label="选择日期",
widget = widgets.DateInput(attrs={"type":"date"})
)
files = fields.FilePathField(path="./MyProject",
allow_folders=True,recursive=True)
ip = fields.GenericIPAddressField(protocol="both",unpack_ipv4=False)
def index(request):
if request.method=="GET":
form = MyForm()
return render(request,"index.html",{"form":form})
else:
form = MyForm(request.POST)
if form.is_valid():
data = form.cleaned_data
print(data.get("hobby"))
return HttpResponse("hello lyshark")
重写父类方法 通过form表单重写init方法,实现数据库动态添加,前端动态显示,以两个选择框为例
# name: models.py
from django.db import models
class DBHost(models.Model):
id = models.AutoField(primary_key=True)
host = models.CharField(max_length=32)
title = models.CharField(max_length=32)
# name:index.html
{{ form.title }}
{{ form.host }}
# name:views.py
from django.shortcuts import render
from django.forms import Form,fields,widgets
from MyWeb import models
class DBHost(Form):
title = fields.IntegerField(widget=widgets.Select(choices=[]))
host = fields.IntegerField(widget=widgets.SelectMultiple(choices=[]))
# 重写父类的 __init__ 方法
def __init__(self,*args,**kwargs):
super(DBHost, self).__init__(*args,**kwargs)
self.fields['title'].widget.choices = models.DBHost.objects.all().values_list("id","title")
self.fields['host'].widget.choices = models.DBHost.objects.all().values_list("id", "host")
def index(request):
form = DBHost()
return render(request,"index.html",{"form":form})
给Form表单返回数据 Form表单可以返回默认数据,我们可以通过编号查询到指定数据的默认参数,并返回到编辑框中.
# name:views.py
from django.shortcuts import render
from django.forms import Form,fields,widgets
from MyWeb import models
class MyForm(Form):
host = fields.CharField(required=True,widget=widgets.TextInput())
title = fields.CharField(required=True, widget=widgets.TextInput())
def index(request):
nid = request.GET.get("id") # 通过ID获取到记录
qset = models.DBHost.objects.filter(id=nid).values("host","title")
dic = qset[0] # 转为字典
form = MyForm(dic) # 传递到前端编辑框中
return render(request,"index.html",{"form":form})