日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Auth模块、Forms组件

發布時間:2025/4/16 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Auth模块、Forms组件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Auth模塊

auth模塊是Django自帶的用戶認證模塊:

我們在開發一個網站的時候,無可避免的需要設計實現網站的用戶系統。此時我們需要實現包括用戶注冊、用戶登錄、用戶認證、注銷、修改密碼等功能,這還真是個麻煩的事情呢。

Django作為一個完美主義者的終極框架,當然也會想到用戶的這些痛點。它內置了強大的用戶認證系統--auth,它默認使用 auth_user 表來存儲用戶數據。

?為了方便快捷的幫開發者完成登錄相關的認證交互功能。

auth_user表常用操作:

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')#獲取第一個用戶 user = User.objects.first()#修改密碼 user.set_password('000') user.save() #注:修改完成后必須要進行保存,即執行save()方法#校驗密碼 res = user.check_password('000')

auth組件常用功能:

# 校驗用戶賬號及密碼,校驗成功返回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())

若用戶沒有登錄,則會跳轉到django默認的 登錄URL '/accounts/login/ ' 并傳遞當前訪問url的絕對路徑 (登陸成功后,會重定向到該路徑)。

如果需要自定義登錄的URL,則需要在settings.py文件中通過LOGIN_URL進行修改。

# 在settings.py中設置: LOGIN_URL = '/login/' # 這里配置成你項目登錄頁面的路由

擴展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'# 在視圖函數中導入的模塊就是: 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":# 校驗請求的所有數據check_form = CheckForm(request.POST)if check_form.is_valid():# 查看校驗成功的數據,為字典類型print(check_form.cleaned_data)return HttpResponse('注冊成功')else:# 查看校驗失敗的數據,為封裝的字典類型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>

組件的參數設置:

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('不能以數字開頭')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="確認密碼",widget=forms.PasswordInput(attrs={'placeholder': '請確認密碼'}))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 == '確認密碼' %}<span style="color: red">{{ all_error.0 }}</span>{% endif %}</p>{% endfor %}<input type="submit" value="注冊"> </form>

?

轉載于:https://www.cnblogs.com/wangke0917/p/10526257.html

總結

以上是生活随笔為你收集整理的Auth模块、Forms组件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。