from django.contrib.auth.models import User # 一、建立普通用戶 User.objects.create_user(username='Owen', password='123') # 二、建立超級用戶 User.objects.create_superuser(username='root', password='root', email='root@root.com') # 此方法django內部源碼未給email傳入默認參數,所以此處須要手動傳值才能建立 # 三、獲取第一個用戶 user = User.objects.first() # 四、修改密碼 user.set_password('000') user.save() # 修改時必定要記得保存 # 五、校驗密碼 res = user.check_password('000')
# 一、校驗用戶帳號及密碼,校驗成功返回user對象 from django.contrib.auth import authenticate user = authenticate(username=usr, password=pwd) # 二、註冊用戶到request對象中,註冊成功能夠request.user訪問當前登陸用戶(會造成session記錄) from django.contrib.auth import login login(request, user) # 註冊authenticate成功(當前登陸)的用戶 # 三、註銷當前註冊的user (用戶註銷) from django.contrib.auth import logout logout(request) # 四、校驗用戶登陸狀態 # 視圖函數中使用 if request.user.is_authenticated(): pass # 模板語言中使用 {% if request.user.is_authenticated %} {% else %} {% endif %} # 五、校驗登陸狀態的裝飾器 from django.contrib.auth.decorators import login_required @login_required(login_url='/user_login/') def user_home(request): return render(request, 'user.html', locals())
# app/models.py from django.contrib.auth.models import AbstractUser class User(AbstractUser): # 增長自定義字段 info = models.TextField(null=True) # settings.py配置 AUTH_USER_MODEL = 'app.User'
1. 校驗的字段屬性名要與校驗的表單form的表單元素name值進行匹配 2. 校驗字段的參數required,默認爲True(也與自定義True),表明數據必須傳入該校驗值,若是設置爲False,校驗數據中能夠不包含該校驗值 3. error_messages自定義校驗規則的校驗失敗的(中)錯誤信息 from django import forms class CheckForm(forms.Form): usr = forms.CharField(min_length=3, max_length=10) pwd = forms.CharField( min_length=3, max_length=10, error_messages={ "min_length": "最少3", # 某個校驗規則對應的 中文提示 錯誤信息 "max_length": "最多10", 'required': "必填項" # 除了自定義校驗規則,還能夠明確默認校驗規則的 中文提示 錯誤信息 } ) def register(request): check_form = CheckForm(request.POST) if check_form.is_valid(): print("校驗成功") print(check_form.cleaned_data) else: print("校驗失敗") print(check_form.cleaned_data) # 部分紅功的數據 # from django.forms.utils import ErrorDict print(check_form.errors) # 部分失敗的信息
html
class CheckForm(forms.Form): usr = forms.CharField(...) # ... # 局部鉤子 def clean_usr(self): cleaned_usr = self.cleaned_data.get('usr', None) # 自定義校驗規則 import re if re.match('^[0-9]', cleaned_usr): # 經過正則匹配不能以數字開頭 from django.core.exceptions import ValidationError raise ValidationError('不能以數字開頭') # 拋ValidationError信息就會被添加到self.errors中 return cleaned_usr
django
class CheckForm(forms.Form): # ... # 全局鉤子 def clean(self): cleaned_pwd = self.cleaned_data.get('pwd', None) cleaned_re_pwd = self.cleaned_data.get('re_pwd', None) if cleaned_pwd != cleaned_re_pwd: from django.core.exceptions import ValidationError raise ValidationError('兩次密碼不一致') # 拋ValidationError信息就會被添加到self.errors中 return self.cleaned_data
class CheckForm2(forms.Form): # 校驗需求:帳號必須不能以數字開頭 usr = forms.CharField(min_length=3, max_length=10, label="帳號:", error_messages={ 'required': "必填項", 'min_length': "最少3", 'max_length': "最多10" }) pwd = forms.CharField(min_length=3, max_length=10, label="密碼:", error_messages={ 'required': "必填項", 'min_length': "最少3", 'max_length': "最多10" }, widget=forms.PasswordInput(attrs={ 'class': 'pwd', 'placeholder': '請輸入密碼' }) ) re_pwd = forms.CharField(min_length=3, max_length=10, label="確認:", error_messages={ 'required': "必填項", 'min_length': "最少3", 'max_length': "最多10" }, widget=forms.PasswordInput) email = forms.EmailField(label="郵箱:", error_messages={ 'invalid': "格式不正確", 'required': "必填項" } ) # 局部鉤子:對usr進行局部鉤子的校驗,該方法會在usr屬性校驗經過後,系統調用該方法繼續校驗 def clean_usr(self): cleaned_usr = self.cleaned_data.get('usr', None) # type: str # 經過正則匹配不能以數字開頭 import re if re.match('^[0-9]', cleaned_usr): from django.core.exceptions import ValidationError raise ValidationError('不能以數字開頭') return cleaned_usr # 全局鉤子:表明校驗類中的全部屬性校驗經過後,系統調用該方法繼續校驗 def clean(self): cleaned_pwd = self.cleaned_data.get('pwd', None) cleaned_re_pwd = self.cleaned_data.get('re_pwd', None) if cleaned_pwd != cleaned_re_pwd: from django.core.exceptions import ValidationError raise ValidationError('兩次密碼不一致') return self.cleaned_data def register2(request): if request.method == "GET": check_form2 = CheckForm2() if request.method == "POST": check_form2 = CheckForm2(request.POST) if check_form2.is_valid(): return HttpResponse('註冊成功') else: print(check_form2.errors.as_data) all_error = check_form2.errors.get('__all__') return render(request, 'register2.html', locals())
<form action="" method="post" novalidate> {% for ele in check_form2 %} <p> <label for="">{{ ele.label }}</label> {{ ele }} <span style="color: red;">{{ ele.errors.0 }}</span> {% if ele == check_form2.re_pwd %} <span style="color: red;">{{ all_error.0 }}</span> {% endif %} </p> {% endfor %} <input type="submit" value="註冊"> </form>