django域名反向解析、類檢視、利用建立類的方式對預設表格進行修改、檢查郵箱是否被註冊、更改密碼介面
阿新 • • 發佈:2018-12-13
域名反向解析:當路徑發生改變後固定路徑需要改變,通過反向解析可以自動尋找並修改
huasheng/urls.py下 新增namespace
url(r'^user/',include('user.urls',namespace='user')),
各應用urls.py下 新增name
url(r'^$', views.index,name='index'),
html模板中
<form action="{% url 'user:register' %}" method="POST">user找姓register找名
檢視函式和類檢視
views.py下 from django.shortcuts import render,redirect #redirect重定向 from django.core.urlresolvers import reverse #匯入反向解析函式 from django.http import HttpResponse from .models import User from django.views.generic import View #匯入View類 class RegisterView(View): def get(self,request): #當method為get時執行 return render(request, 'register.html') def post(self,request): #當method是post時執行 user_name = request.POST.get('user_name') pwd = request.POST.get('pwd') email = request.POST.get('email') allow = request.POST.get('allow') print(allow) # 校驗資料是否為空 if not all([user_name, pwd, email, allow]): return HttpResponse('資料有為空的情況') # 校驗資料格式的情況 user = User.objects.create_user(username=user_name, email=email, password=pwd) # username, email = None, password = None, ** extra_fields user.is_active = 0 #將is_active屬性改為0並儲存 user.save() return redirect(reverse('carlist:index')) #重定向到首頁 urls.py下更改 url(r'register/',views.RegisterView.as_view(),name='register') #跳轉到views.RegisterView.as_view()判斷method
利用建立類的方式對預設表格進行修改
apps資料夾下建立db資料夾下base_model.py from django.db import models class BaseModel(models.Model): is_delete = models.BooleanField(default=False,verbose_name='是否刪除') #新增is_delete create_time = models.DateTimeField(auto_now_add=True,verbose_name='建立時間') #新增create_time class Meta: abstract = True #註冊類
應用下models.py中
from db.base_model import BaseModel
from django.contrib.auth.models import AbstractUser
class User(AbstractUser,BaseModel): #讓User類繼承BaseModel類將新屬性新增進預設表結構中
pass
###***注意遷移出錯刪庫時不要忘記刪除對應migrations檔案
檢查郵箱是否被註冊
reemail = User.objects.filter(email=email) if len(reemail)!=0: return HttpResponse('郵箱已被註冊')
更改密碼介面
寫好對應html,配置好url
veiw.py中新增新類ChangePwd
class ChangePwd(View):
def get(self,request):
return render(request, 'changepwd.html')
def post(self,request):
user_name = request.POST.get('user_name')
pwd = request.POST.get('pwd')
new_pwd = request.POST.get('new_pwd')
new_cpwd = request.POST.get('new_cpwd')
# print(allow)
# 校驗資料是否為空
print(user_name)
print(pwd)
print(new_pwd)
print(new_cpwd)
if not all([user_name, pwd, new_pwd, new_cpwd]):
return HttpResponse('資料有為空的情況')
try:
user = User.objects.get(username = user_name)
except Exception:
return HttpResponse('賬號不存在')
if new_pwd!=new_cpwd:
return HttpResponse('兩次密碼輸入不一致')
if not user.check_password(pwd):
print(user)
return HttpResponse('密碼錯誤')
# 校驗資料格式的情況
user.set_password(new_pwd)
user.save()
# username, email = None, password = None, ** extra_fields
return redirect(reverse('carlist:index'))