Auth模块、Forms组件
生活随笔
收集整理的這篇文章主要介紹了
Auth模块、Forms组件
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Auth模塊
auth模塊是Django自帶的用戶認(rèn)證模塊:
我們在開發(fā)一個網(wǎng)站的時候,無可避免的需要設(shè)計實現(xiàn)網(wǎng)站的用戶系統(tǒng)。此時我們需要實現(xiàn)包括用戶注冊、用戶登錄、用戶認(rèn)證、注銷、修改密碼等功能,這還真是個麻煩的事情呢。
Django作為一個完美主義者的終極框架,當(dāng)然也會想到用戶的這些痛點。它內(nèi)置了強(qiáng)大的用戶認(rèn)證系統(tǒng)--auth,它默認(rèn)使用 auth_user 表來存儲用戶數(shù)據(jù)。
?為了方便快捷的幫開發(fā)者完成登錄相關(guān)的認(rèn)證交互功能。
auth_user表常用操作:
from django.contrib.auth.models import User #創(chuàng)建普通用戶 User.objects.create_user(username='Owen', password='123')#創(chuàng)建超級用戶 User.objects.create_superuser(username='root',password='root',email='root@root.com')#獲取第一個用戶 user = User.objects.first()#修改密碼 user.set_password('000') user.save() #注:修改完成后必須要進(jìn)行保存,即執(zhí)行save()方法#校驗密碼 res = user.check_password('000')auth組件常用功能:
# 校驗用戶賬號及密碼,校驗成功返回user對象 from django.contrib.auth import authenticate #該模塊需要兩個參數(shù),用戶名和密碼 user=authenticate(username=usr, password=pwd)# 注冊用戶到request對象中,注冊成功可以用request.user訪問當(dāng)前登錄用戶(會形成session記錄) from django.contrib.auth import login login(request, user) # 注冊authenticate成功(當(dāng)前登錄)的用戶# 注銷當(dāng)前注冊的user(用戶注銷) from django.contrib.auth import logout logout(request)# 校驗用戶登錄狀態(tài) # 視圖函數(shù)中使用 if request.user.is_authenticated(): pass # 模板語言中使用 {% if request.user.is_authenticated %} {% else %} {% endif %}# 校驗登錄狀態(tài)的裝飾器 from django.contrib.auth.decorators import login_required @login_required(login_url='/user_login/') def user_home(request):return render(request, 'user.html', locals())若用戶沒有登錄,則會跳轉(zhuǎn)到django默認(rèn)的 登錄URL '/accounts/login/ ' 并傳遞當(dāng)前訪問url的絕對路徑 (登陸成功后,會重定向到該路徑)。
如果需要自定義登錄的URL,則需要在settings.py文件中通過LOGIN_URL進(jìn)行修改。
# 在settings.py中設(shè)置: LOGIN_URL = '/login/' # 這里配置成你項目登錄頁面的路由擴(kuò)展User表:
# 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'# 在視圖函數(shù)中導(dǎo)入的模塊就是: from app.models import User#第二種方式:(不建議使用)from django.contrib.auth.models import User Create your models here. class UserInfo(models.Model):id = models.AutoField(primary_key=True)info = models.TextField(null=True)user = models.OneToOneField(to=User, to_field='username', db_constraint=False, null=True, on_delete=models.SET_NULL)
Forms組件
表單字段的校驗:
<!-- register.html核心代碼 --> <form action="" method="post" novalidate><input type="text" name="usr"><input type="password" name="pwd"><input type="email" name="email"><input type="submit" value="注冊"> </form> # views.py核心代碼 from django.shortcuts import render, HttpResponse from django import forms # 自定義校驗表單字段的類,繼承forms.Form,并用forms下具體字段完成校驗 class CheckForm(forms.Form):# 通過error_messages自定義錯誤信息usr = forms.CharField(min_length=3, max_length=10, error_messages={'min_length':'長度至少為3'})pwd = forms.CharField(min_length=3, max_length=10)email = forms.EmailField(error_messages={'invalid':'郵箱不合法', 'required': '必填項'})def register(request):if request.method == "GET":return render(request, 'register.html')if request.method == "POST":# 校驗請求的所有數(shù)據(jù)check_form = CheckForm(request.POST)if check_form.is_valid():# 查看校驗成功的數(shù)據(jù),為字典類型print(check_form.cleaned_data)return HttpResponse('注冊成功')else:# 查看校驗失敗的數(shù)據(jù),為封裝的字典類型print(check_form.errors)return HttpResponse('注冊失敗')表單元素的渲染:
# view.py改動代碼 class CheckForm(forms.Form):usr = forms.CharField(min_length=3, max_length=10, label="用戶名")pwd = forms.CharField(min_length=3, max_length=10, label="密碼")email = forms.EmailField(, label="郵箱")def register(request):if request.method == "GET":check_form = CheckForm()return render(request, 'register.html', {'check_form': check_form}) <!-- register.html核心代碼 --> <!-- 方式一 --> <form action="" method="post">{{ check_form.usr }}{{ check_form.pwd }}{{ check_form.email }}<input type="submit" value="注冊"> </form> <!-- 方式二 --> <form action="" method="post">{% for foo in check_form %} <label for="{{ foo.id_for_label }}" class="col-sm-2 control-label">{{ foo.label }}</label> {{ foo }} {% endfor %}<input type="submit" value="注冊"> </form> <!-- 方式三 --> <form action="" method="post"><table>{{ check_form.as_table}}</table><input type="submit" value="注冊"> </form> <!-- 方式四 --> <form action="" method="post"><ul>{{ check_form.as_ul}}</ul><input type="submit" value="注冊"> </form> <!-- 方式五 --> <form action="" method="post">{{ check_form.as_p}}<input type="submit" value="注冊"> </form>錯誤信息的渲染:
# views.py class CheckForm(forms.Form):usr = forms.CharField(min_length=3,max_length=10,error_messages={'min_length': '長度至少為3','max_length': '長度最多為10','required': '必填項'},label="用戶名")pwd = forms.CharField(min_length=3,max_length=10,error_messages={'min_length': '長度至少為3','max_length': '長度最多為10','required': '必填項'},label="密碼")email = forms.EmailField(error_messages={'invalid': '郵箱不合法','required': '必填項'})def register(request):if request.method == "GET":check_form = CheckForm()if request.method == "POST":check_form = CheckForm(request.POST)if check_form.is_valid():return HttpResponse('注冊成功')return render(request, 'register.html', locals()) <form action="" method="post" novalidate>{% for ele in check_form %}<p>{{ ele.label }}:{{ ele }}<span style="color: red">{{ ele.errors.0 }}</span></p>{% endfor %}<input type="submit" value="注冊"> </form>組件的參數(shù)設(shè)置:
class Ret(Form):name = forms.CharField(max_length=10, min_length=2, label='用戶名',error_messages={'required': '該字段不能為空', 'invalid': '格式錯誤', 'max_length': '太長','min_length': '太短'},widget=widgets.TextInput(attrs={'class':'form-control'}))pwd = forms.CharField(max_length=10, min_length=2, widget=widgets.PasswordInput(attrs={'class':'form-control'}))email = forms.EmailField(label='郵箱', error_messages={'required': '該字段不能為空', 'invalid': '格式錯誤'})局部鉤子:
# 在自定義驗證類CheckForm中添加局部驗證鉤子 class CheckForm(forms.Form):...def clean_usr(self):name = self.cleaned_data.get('usr') # type: strimport reif re.match('^[0-9]', name):from django.core.exceptions import ValidationErrorraise ValidationError('不能以數(shù)字開頭')return name全局鉤子:
# views.py class CheckForm(forms.Form):usr = forms.CharField(min_length=3,max_length=10,error_messages={'min_length': '長度至少為3','max_length': '長度最多為10','required': '必填項'},label="用戶名",widget=forms.TextInput(attrs={'placeholder': '請輸入用戶名'}))pwd = forms.CharField(min_length=3,max_length=10,error_messages={'min_length': '長度至少為3','max_length': '長度最多為10','required': '必填項'},label="密碼",widget=forms.PasswordInput(attrs={'placeholder': '請輸入密碼'}))re_pwd = forms.CharField(min_length=3,max_length=10,error_messages={'min_length': '長度至少為3','max_length': '長度最多為10','required': '必填項'},label="確認(rèn)密碼",widget=forms.PasswordInput(attrs={'placeholder': '請確認(rèn)密碼'}))def clean(self):pwd = self.cleaned_data.get('pwd')re_pwd = self.cleaned_data.get('re_pwd')if pwd == re_pwd:return self.cleaned_datafrom django.core.exceptions import ValidationErrorraise ValidationError('兩次密碼不一致')def register(request):if request.method == "GET":check_form = CheckForm()if request.method == "POST":check_form = CheckForm(request.POST)if check_form.is_valid():return HttpResponse('注冊成功')else:# 拿到全局鉤子拋出的錯誤信息all_error = check_form.errors.get('__all__', None)return render(request, 'register.html', locals()) <form action="" method="post" novalidate>{% for ele in check_form %}<p>{{ ele.label }}:{{ ele }}<span style="color: red">{{ ele.errors.0 }}</span>{% if ele.label == '確認(rèn)密碼' %}<span style="color: red">{{ all_error.0 }}</span>{% endif %}</p>{% endfor %}<input type="submit" value="注冊"> </form>?
轉(zhuǎn)載于:https://www.cnblogs.com/wangke0917/p/10526257.html
總結(jié)
以上是生活随笔為你收集整理的Auth模块、Forms组件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 循环神经网络-Dropout
- 下一篇: 【RAY TRACING THE RES