08.form组件
form組件
在需要使用用戶認證組件的app下創建my_form.py
# my_form.py from django.forms import widgets # 用于規定type from django import forms # forms組件 from blog.models import UserInfo # 引入表進行創建鉤子 from django.core.exceptions import ValidationError # 鉤子捕獲異常class UserForm(forms.Form):user = forms.CharField(max_length=32, label="用戶名", widget=widgets.TextInput(attrs={"class": "form-control"}),error_messages={"required": "該字段不能為空"})pwd = forms.CharField(max_length=32, label="密碼", widget=widgets.PasswordInput(attrs={"class": "form-control"}),error_messages={"required": "該字段不能為空"})re_pwd = forms.CharField(max_length=32, label="確認密碼", widget=widgets.PasswordInput(attrs={"class": "form-control"}),error_messages={"required": "該字段不能為空"})email = forms.EmailField(max_length=32, label="郵箱", widget=widgets.EmailInput(attrs={"class": "form-control"}),error_messages={"required": "該字段不能為空"})# 二次校驗def clean_user(self):user = self.cleaned_data.get("user")userinfo = UserInfo.objects.filter(username=user).first()if not userinfo:return userelse: # 已有人注冊過了raise ValidationError("該用戶已被注冊") # 一定要用raise ValidationError("xxxxx")def clean(self): # 全局鉤子,鍵__all__pwd = self.cleaned_data.get("pwd") # 所有干凈的字段以及對應的值的字典re_pwd = self.cleaned_data.get("re_pwd")# 有多個錯誤信息需要再多一個判斷if pwd and re_pwd: # 兩個都有值時if pwd.upper() == re_pwd.upper():return self.cleaned_dataelse:raise ValidationError("兩次密碼不一致")else:return self.cleaned_data# register.html {% for field in form %}<div class="form-group"><label for="{{ field.auto_id }}">{{ field.label }}</label>#.auto_id生成id_field,用于label對應input的id{{ field }} <span class="error pull-right"></span></div> {% endfor %}#views.register if form.is_valid(): # 如果有值response["user"] = form.cleaned_data.get("user")# 生成用戶信息user = form.cleaned_data.get("user")pwd = form.cleaned_data.get("pwd")email = form.cleaned_data.get("email")avatar_obj = request.FILES.get("avatar") # 拿頭像print(form.cleaned_data)# 代碼優化extra = {} # 擴展字段if avatar_obj: # 如果用戶傳了頭像extra["avatar"] = avatar_obj # 擴展字段賦值給字典 UserInfo.objects.create_user(username=user, password=pwd, email=email, **extra) # 傳字典**{}else: # 如果沒有值,則說明有錯誤form.errors拿到所有錯誤的字典print(form.cleaned_data)print(form.errors)response["msg"] = form.errors?
轉載于:https://www.cnblogs.com/QQL-anatkh/p/9597630.html
總結
- 上一篇: html-head-body
- 下一篇: Android实战——第三方服务之Bmo