DjangoWeb开发--登陆页面及权限的设置与使用
1.django自带的登陆页面使用的是Username和Password,我们可以通过自定义用邮箱来登陆
from django.shortcuts import render_to_response
from django import forms
class LoginForm(forms.Form):
# 继承表单模块
email = forms.CharField(label='email:', max_length=100)
pwd = forms.CharField(label='password', widget=forms.PasswordInput)
#隐式输入密码
def login(request):
if ('email' or 'pwd') not in request.GET:
lf = LoginForm()
return render_to_response('login.html', {'lf':lf})
# "login.html"对应的模板语法为{{lf.as_p}}
lf = LoginForm(request.GET)
email = lf.data['email']
pwd = lf.data['pwd']
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
pass
else:
if user.check_password(pwd):
if user.has_perm('blog.can_view'): #检查用户权限
# do something
return HttpResponse("you can see news")
return HttpResponse("you can't see news")
return HttpResponseRedirect('/blog/login')
2.权限设计和使用
# 为要设置权限的表添加元属性
class Meta:
permissions = {('can_view', 'can see news'), ('can_add', 'can add news'),
('can_edit', 'can edit news'), ('can_delete', 'can delete news')}
from django.contrib.auth.models import Permission
import uuid
def register(request):
if ('email' or 'pwd') not in request.GET:
lf = LoginForm()
return render_to_response('login.html',
lf = LoginForm(request.GET)
email = lf.data['email']
pwd = lf.data['pwd']
user = User()
user.username = uuid.uuid()
user.email = email
user.set_password(pwd)
user.desc = 'lazy'
user.save()
user.user_permissions = [Permission.objects.get(codename='can_view'), \
Permissions.objects.get(codename='can_add')]
user.save()
return HttpResponseRedict('/blog/login')
网友评论