Pythonfrom django import forms
class BootStrap:
# 排除此列表中的BootStrap样式
bootstrap_exclude_field = []
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 循环ModelForm中的所有字段,给每个字段的插件设置
for name, field in self.fields.items():
if name in self.bootstrap_exclude_field:
continue
# 字段中有属性,保留原来的属性,没有属性,才增加。
if field.widget.attrs:
field.widget.attrs["class"] = "form-control"
field.widget.attrs["placeholder"] = field.label
else:
field.widget.attrs = {
"class": "form-control",
"placeholder": field.label
}
class BootStrapModelForm(BootStrap, forms.ModelForm):
pass
class BootStrapForm(BootStrap, forms.Form):
pass
Pythonclass AdminModelForm(BootStrapModelForm):
confirm_password = forms.CharField(
label="确认密码",
widget=forms.PasswordInput(render_value=True)
)
class Meta:
model = models.Admin
fields = ["username", "phone", "email", 'password', "confirm_password", ]
widgets = {
# render_value=True 当提交密码保错的时不会清空
"password": forms.PasswordInput(render_value=True)
}
def clean_password(self):
pwd = self.cleaned_data.get("password")
return md5(pwd)
# 确认密码验证
def clean_confirm_password(self):
pwd = self.cleaned_data.get("password")
confirm = md5(self.cleaned_data.get("confirm_password"))
if confirm != pwd:
raise ValidationError("密码不一致")
# 返回什么,此字段以后保存到数据库就是什么。
return confirm
def admin_add(request):
""" 添加管理员 """
title = "新建管理员"
if request.method == "GET":
form = AdminModelForm()
return render(request, 'change.html', {'form': form, "title": title})
form = AdminModelForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('/admin/list/')
return render(request, 'change.html', {'form': form, "title": title})
html{% extends 'layout.html' %}
{% block title %}{{ title }}{% endblock %}
{% block content %}
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"> {{ title }} </h3>
</div>
<div class="panel-body">
<form method="post" novalidate>
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label>{{ field.label }}</label>
{{ field }}
<span style="color: red;">{{ field.errors.0 }}</span>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">提 交</button>
</form>
</div>
</div>
</div>
{% endblock %}
Pythonclass Admin(models.Model):
""" 管理员表 """
username = models.CharField(verbose_name='用户名', max_length=32)
password = models.CharField(verbose_name='密码', max_length=64)
phone = models.CharField(verbose_name='手机号', max_length=32)
email = models.CharField(verbose_name='邮箱', max_length=32)
# 返回模型的字符串表示形式,即用户名
# 当调用 str() 方法时,会返回管理员的用户名
def __str__(self):
return self.username
本文作者:GYC
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!