本篇是在完成用戶登錄登出,密碼修改功能后,擴(kuò)展用戶注冊功能。
關(guān)于用戶登錄、注銷、更改密碼和重置密碼。請查看
Django身份驗證初試-CSDN博客
Django登錄注銷視圖-CSDN博客
Django密碼修改和重置視圖-CSDN博客
用戶注冊
創(chuàng)建一個表單,讓用戶輸入用戶名、真實姓名和密碼。
編輯位于account應(yīng)用程序目錄中的forms.py文件
from django.contrib.auth.models import User
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(label='Passowrd',widget=forms.PasswordInput)
password2 = forms.CharField(label='Repeat passowrd',widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username','first_name','email')
def clean_password2(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError("Passwords don't match.")
return cd['password2']
- 表單中包含username,first_name,email字段,這些字段講根據(jù)它們對應(yīng)的模型進(jìn)行驗證。如果用戶填寫了一個已經(jīng)存在的用戶名,將得到一個驗證錯誤。因為username是一個用unique=True定義的字段。
- 添加password和password2兩個字段,用來確認(rèn)密碼。
- 定義了一個clean_password2方法,用于對照第一個密碼檢查第二個密碼,如果密碼不匹配,則不讓表單驗證。這個檢查是在調(diào)用is_valid方法時完成的。
??Django可以為任何表單字段提供clean_<fieldname>()方法,清楚特定字段的值或引發(fā)表單驗證錯誤。表單還包括一個通用的clean()方法來驗證整個表單,這對于驗證相互依賴的字段非常有用。
??Django還提供了一個UserCreationForm表單,它位于Django .contrib.auth.forms中,和剛才創(chuàng)建的表單非常相似。
編輯account應(yīng)用程序的views.py文件
from .forms import EmailPostForm,CommentForm,SearchForm,UserRegistrationForm
def register(request):
if request.method == 'POST':
user_form = UserRegistrationForm(request.POST)
if user_form.is_valid():
new_user = user_form.save(commit=False)
new_user.set_password(user_form.cleaned_data['password'])
new_user.save()
template = "account/register_done.html"
context = {'new_user':new_user}
return render(request,template,context)
else:
user_form = UserRegistrationForm()
template = "account/register.html"
context = {'user_form':user_form}
return render(request,template,context)
這里沒有保存用戶輸入的原始密碼,而是使用處理加密的用戶模型的set_password()方法進(jìn)行保存,以保證安全。
編輯account應(yīng)用的urls.py文件,添加如下URL模式:
path('register/',views.register,name='register'),
在account/ template目錄下創(chuàng)建一個新模板,命名為register.html,并使其看起來如下:
{% extends "base.html" %}
{% block title %}Create an account{% endblock %}
{% block content %}
<h1>Create an account</h1>
<p>Please, sign up using the following form:</p>
<form action="." method="post">
{{ user_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Create my account"></p>
</form>
{% endblock %}
在同一目錄下添加一個模板文件,并將其命名register_done.html。將以下代碼添加到其中:
{% extends "base.html" %}
{% block title %}Welcome{% endblock %}
{% block content %}
<h1>Welcome {{ new_user.first_name }}!</h1>
<p>Your account has been successfully created. Now you can
<a href="{% url 'login' %}">log in</a>.</p>
{% endblock %}
用戶模型擴(kuò)展
編輯account應(yīng)用程序的models.py文件
from django.db import models
from django.conf import settings
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
date_of_birth = models.DateField(blank=True, null=True)
photo = models.ImageField(upload_to='users/%Y/%m/%d',blank=True)
def __str__(self):
return 'Profile for user {}'.format(self.user.username)
??為了保持代碼的泛型,請使用get_user_model()方法檢索用戶模型和AUTH_USER_MODEL設(shè)置,以便在定義模型與用戶模型的關(guān)系時引用它,而不是直接引用auth用戶模型。
- 用戶一對一字段允許您將配置文件與用戶關(guān)聯(lián)。on_delete參數(shù)使用CASCADE,這樣當(dāng)用戶被刪除時,它的相關(guān)配置文件也會被刪除。
- 照片字段是一個ImageField字段。您需要安裝Pillow庫來處理圖像。
在shell中運(yùn)行以下命令安裝Pillow:
python -m pip install pillow
為了讓Django在開發(fā)服務(wù)器上為用戶上傳的媒體文件提供服務(wù),在項目的settings.py文件中添加以下設(shè)置:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
- MEDIA_URL是為用戶上傳的媒體文件提供服務(wù)的基本URL,
- MEDIA_ROOT是媒體文件所在的本地路徑。
- Django動態(tài)地構(gòu)建相對于項目路徑的路徑,以使代碼更加通用。
編輯項目的主urls.py文件,修改代碼如下:
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
??Django開發(fā)服務(wù)器將負(fù)責(zé)在開發(fā)過程中提供媒體文件(也就是DEBUG設(shè)置為True時)。
static()輔助函數(shù)適合于開發(fā),但不適合生產(chǎn)使用。永遠(yuǎn)不要在生產(chǎn)環(huán)境中使用Django提供靜態(tài)文件。
編輯account應(yīng)用程序的admin.py文件,并在管理站點(diǎn)中注冊Profile模型,如下所示:
from django.contrib import admin
from .models import Profile
@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
list_display = ['user','date_of_birth','photo']
讓用戶在網(wǎng)站上編輯自己的個人資料。
將以下導(dǎo)入和模型表單添加到account應(yīng)用程序的forms.py文件中:
class UserEditForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name','last_name','email')
class ProfileEditForm(forms.ModelForm):
class Meta:
model = Profile
- UserEditForm:允許用戶編輯自己的名字、姓氏和電子郵件,這些都是Django內(nèi)置用戶模型的屬性。
- ProfileEditForm:這將允許用戶編輯我們保存在自定義概要模型中的概要數(shù)據(jù)。用戶將能夠編輯自己的出生日期,并上傳照片作為個人資料。
編輯account應(yīng)用程序的views.py文件并導(dǎo)入Profile模型,如下所示:
@login_required
def edit(request):
if request.method == 'POST':
user_form = UserEditForm(instance=request.user,data=request.POST)
profile_form = ProfileEditForm(instance=request.user.profile,data=request.POST,files=request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
else:
user_form = UserEditForm(instance=request.user)
profile_form = ProfileEditForm(instance=request.user.profile)
template = "account/edit.html"
context = {'user_form':user_form}
return render(request,template,context)
- 使用login_required裝飾器是因為用戶必須經(jīng)過身份驗證才能編輯他們的配置文件。
- UserEditForm用于存儲內(nèi)置用戶模型的數(shù)據(jù)
- ProfileEditForm用于存儲自定義概要模型中的附加概要數(shù)據(jù)。
- 為了驗證提交的數(shù)據(jù),將執(zhí)行兩個表單的is_valid()方法。如果兩個表單都包含有效的數(shù)據(jù),將保存兩個表單,調(diào)用save()方法來更新數(shù)據(jù)庫中相應(yīng)的對象。
將以下URL模式添加到account應(yīng)用程序的urls.py文件中:文章來源:http://www.zghlxwxcb.cn/news/detail-798707.html
{% extends "base.html" %}
{% block title %}Edit your account{% endblock %}
{% block content %}
<h1>Edit your account</h1>
<p>You can edit your account using the following form:</p>
<form action="." method="post" enctype="multipart/form-data">
{{ user_form.as_p }}
{{ profile_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Save changes"></p>
</form>
{% endblock %}
表單中包含enctype="multipart/form-data"來啟用文件上傳。
使用HTML表單來提交user_form和profile_form表單。文章來源地址http://www.zghlxwxcb.cn/news/detail-798707.html
到了這里,關(guān)于Django用戶注冊和用戶配置擴(kuò)展的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!