我是看的Django Book的教程,然后用最原始的方式实现的。请问关于登录和注册,Django有没有封装像ListView, DetailView, FormView这样的class来直接实现呢?
这是login代码的实现
def user_login(request):
if request.POST:
username = password = ''
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request, user)
return redirect('/')
else:
context = {}
return render(request, 'account/login.html', context)
这是register代码的实现
def user_register(request):
if request.method == "POST":
register_form = UserForm(request.POST)
if register_form.is_valid():
username = register_form.cleaned_data['username']
password = register_form.cleaned_data['password']
email = register_form.cleaned_data['email']
user = User.objects.create_user(username, email, password)
user.save()
login(request, authenticate(username=username, password=password))
return redirect('/')
else:
register_form = UserForm()
context = {'register_form': register_form}
return render(request, 'account/register.html', context)
这是logout代码的实现
def user_logout(request):
logout(request)
return redirect('/')
黄舟2017-04-18 09:47:54
先登陸你一定要算一個session或cookies給前端,這樣在登陸之後,以後前端就會拿著這個算好的session或者cookies上來找你,說我已經登陸了,這是我登陸的憑據,然後伺服器端拿到之後,計算一下是不是跟我算出來的一樣,如果是說明是正常登陸了。而不是 簡單的跳轉一個頁面,什麼也訊息也不回傳。
註冊這個不用說了吧。 。就是往資料庫裡面寫帳號密碼,然後用回登陸的時候然後比對,正確了就跳轉登陸。
登出就是清理掉該用戶的登陸信息,比如cookies刷新session啥的,檢測不到了之後就會不能訪問登陸後的頁面了就跳轉重定向到登陸頁面就可以了。
巴扎黑2017-04-18 09:47:54
是不是應該驗證從前端傳過來的使用者名稱和密碼呢?
class LoginForm(forms.Form):
email = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
self.user_cache = None
super(LoginForm, self).__init__(*args, **kwargs)
def clean(self):
email = self.cleaned_data.get('email')
password = self.cleaned_data.get('password')
if email and password:
if not AtUser.objects.filter(email=email).exists():
raise forms.ValidationError(u'该账号不存在')
self.user_cache = authenticate(email=email, password=password)
if self.user_cache is None:
raise forms.ValidationError(u'邮箱或密码错误!')
elif not self.user_cache.is_active:
raise forms.ValidationError(u'该帐号已被禁用!')
return self.cleaned_data
def get_user_id(self):
"""获取用户id"""
if self.user_cache:
return self.user_cache.id
return None
def get_user(self):
"""获取用户实例"""
return self.user_cache
註冊同理