ModelForm的简单使用-注册用modelform编写
Posted pcent
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ModelForm的简单使用-注册用modelform编写相关的知识,希望对你有一定的参考价值。
1.前端的ajax代码不用改动
2.modelform,在原来基础上稍作改动
from django import forms from app01.models import UserInfo from django.forms import widgets as wid from django.core.exceptions import ValidationError import re class UserModelForm(forms.ModelForm): r_password = forms.CharField(min_length=5, label="确认密码", widget=wid.PasswordInput(), error_messages={ "required": "确认密码不能为空!", "min_length": "确认密码不能少于5位!" } ) class Meta: model=UserInfo fields=["username","password","r_password","email"] labels={ "username":"用户名", "password":"密码", "email":"邮箱" } error_messages={ "username":{"required":"用户名不能为空!", "min_length":"用户名不能少于5位!"}, "password":{"required":"密码不能为空!", "min_length": "密码不能少于5位!"}, "email":{"required":"邮箱不能为空!", "invalid":"邮箱格式错误!"} } widgets={"password":wid.PasswordInput()} def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) for field in self.fields.values(): field.widget.attrs.update({"class":"form-control"}) def clean_username(self): val = self.cleaned_data.get("username") user_obj = UserInfo.objects.filter(username=val).first() if user_obj: raise ValidationError("该用户已经存在!") else: return val def clean_password(self): val = self.cleaned_data.get("password") if val.isdigit(): raise ValidationError("密码不能是纯数字!") else: return val def clean_email(self): val = self.cleaned_data.get("email") ret = re.search("\[email protected]$",val) if ret: return val else: raise ValidationError("邮箱必须是163邮箱!") def clean(self): password = self.cleaned_data.get("password") r_password = self.cleaned_data.get("r_password") if password and r_password and password != r_password: self.add_error("r_password",ValidationError("两次密码输入不一致!")) else: return self.cleaned_data
3.视图函数,稍微一改
def reg(request): # 注册功能 if request.method == "POST": ret = json.loads(request.body) form = UserModelForm(ret) res = {"status":200,"err_msg":""} if form.is_valid(): form.save() # del ret["r_password"] # UserInfo.objects.create_user(**ret) else: res["status"] = 201 res["err_msg"] = form.errors return JsonResponse(res) else: form = UserModelForm() return render(request,"reg.html",{"form":form})
modelform的使用
(1) model的知识点:
class UserInfo(AbstractUser):
tel=models.CharField(max_length=32)
gender=models.IntegerField(choices=((1,"男"),(2,"女")),default=1)
yuan=UserInfo.objects.get(pk=1)
yuan.get_gender_display()
(2) modelform使用
model.py:
class Book(models.Model):
nid=models.AutoField(primary_key=True)
title=models.CharField(max_length=32)
price=models.DecimalField(max_digits=8,decimal_places=2) # 999999.99
pub_date=models.DateTimeField() # "2012-12-12"
# comment_count=models.IntegerField(default=100)
# poll_count=models.IntegerField(default=100)
publish=models.ForeignKey(to="Publish",on_delete=models.CASCADE) # 级联删除
authors=models.ManyToManyField(to="Author")
def __str__(self):
return self.title
form.py:
# 构建modelform
class BookModelForm(forms.ModelForm):
class Meta:
model=Book
fields="__all__"
‘‘‘
BookModelForm等同于:
class BookForm(forms.Form):
title=forms.CharField(max_length=32)
price=forms.IntegerField()
pub_date=forms.DateField(widget=widgets.TextInput(attrs={"type":"date"}))
#publish=forms.ChoiceField(choices=[(1,"AAA"),(2,"BBB")])
publish=forms.ModelChoiceField(queryset=Publish.objects.all())
authors=forms.ModelMultipleChoiceField(queryset=Author.objects.all())
‘‘‘
逻辑:
添加书籍:
def add(reqeust):
if GET请求:
form=BookModelForm()
return render(reqeust,{"form":form})
‘‘‘
渲染页面
<form action="" method="post" novalidate>
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label for="title">{{ field.label }}</label>
{{ field }}
<span>{{ field.errors.0 }}</span>
</div>
{% endfor %}
<input type="submit" value="提交" class="btn btn-default pull-right">
</form>
‘‘‘
else POST请求:
form=BookModelForm(request.POST)
if form.is_valid():
form.save() # Book.objects.create(clean_data)
return redirect("/")
else:
return render(reqeust,{"form":form})
编辑书籍:
def edit(request,id):
edit_obj=Book.objects.get(pk=id)
if GET请求:
form=BookModelForm(instance=edit_obj)
return render(reqeust,{"form":form})
‘‘‘
渲染页面同添加页面
‘‘‘
else POST请求:
form=BookModelForm(request.POST,instance=edit_obj)
if form.is_valid():
form.save() # edit_obj.update(clean_data)
return redirect("/")
else:
return render(reqeust,{"form":form})
(1) model的知识点: class UserInfo(AbstractUser): tel=models.CharField(max_length=32) gender=models.IntegerField(choices=((1,"男"),(2,"女")),default=1) yuan=UserInfo.objects.get(pk=1) yuan.get_gender_display() (2) modelform使用 model.py: class Book(models.Model): nid=models.AutoField(primary_key=True) title=models.CharField(max_length=32) price=models.DecimalField(max_digits=8,decimal_places=2) # 999999.99 pub_date=models.DateTimeField() # "2012-12-12" # comment_count=models.IntegerField(default=100) # poll_count=models.IntegerField(default=100) publish=models.ForeignKey(to="Publish",on_delete=models.CASCADE) # 级联删除 authors=models.ManyToManyField(to="Author") def __str__(self): return self.title form.py: # 构建modelform class BookModelForm(forms.ModelForm): class Meta: model=Book fields="__all__" ‘‘‘ BookModelForm等同于: class BookForm(forms.Form): title=forms.CharField(max_length=32) price=forms.IntegerField() pub_date=forms.DateField(widget=widgets.TextInput(attrs={"type":"date"})) #publish=forms.ChoiceField(choices=[(1,"AAA"),(2,"BBB")]) publish=forms.ModelChoiceField(queryset=Publish.objects.all()) authors=forms.ModelMultipleChoiceField(queryset=Author.objects.all()) ‘‘‘ 逻辑: 添加书籍: def add(reqeust): if GET请求: form=BookModelForm() return render(reqeust,{"form":form}) ‘‘‘ 渲染页面 <form action="" method="post" novalidate> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="title">{{ field.label }}</label> {{ field }} <span>{{ field.errors.0 }}</span> </div> {% endfor %} <input type="submit" value="提交" class="btn btn-default pull-right"> </form> ‘‘‘ else POST请求: form=BookModelForm(request.POST) if form.is_valid(): form.save() # Book.objects.create(clean_data) return redirect("/") else: return render(reqeust,{"form":form}) 编辑书籍: def edit(request,id): edit_obj=Book.objects.get(pk=id) if GET请求: form=BookModelForm(instance=edit_obj) return render(reqeust,{"form":form}) ‘‘‘ 渲染页面同添加页面 ‘‘‘ else POST请求: form=BookModelForm(request.POST,instance=edit_obj) if form.is_valid(): form.save() # edit_obj.update(clean_data) return redirect("/") else: return render(reqeust,{"form":form})
以上是关于ModelForm的简单使用-注册用modelform编写的主要内容,如果未能解决你的问题,请参考以下文章