django怎么对密码加密[Django框架]
python+django中使用hashlib库对用户密码进行加密处理
使用hashlib库的sha1对数据进行加密
如:
import hashlibpassword = hashlib.sha1(fr.cleaned_data['password']).hexdigest()
其中fr.cleaned_data['password']是从表单获取到的用户密码
用户登陆的时候,也需要对密码进行加密处理后再进行验证,否则会登陆失败
如下是例子:
views.pydeflogin(request):
username = request.session.get('username',None)
Tasklist = Task.objects.order_by("-id")[0:10]
if request.method == "POST":
fr = loginForm(request.POST)
if fr.is_valid():
username = fr.cleaned_data['username']
password = hashlib.sha1(fr.cleaned_data['password']).hexdigest() #对数据进行sha1加密
name = User.objects.get(user = username).name
user = User.objects.filter(user=username,passwd=password) #数据过滤,这里如果都匹配则返回值,
if user: #判断这个是否有效值
request.session['username'] = name
return HttpResponseRedirect("/")
else: #无效
return HttpResponseRedirect("/login.html",context_instance=RequestContext(request))
else:
fr = loginForm()
return render_to_response('login.html',locals(),context_instance=RequestContext(request))
我在用户注册的时候,是直接在modes.py中进行密码处理的:
class User(models.Model):user = models.IPAddressField(unique=True)
passwd = models.CharField(max_length=100)
name = models.CharField(max_length=100,unique=True)
post = models.CharField(max_length=100)
phone = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
qq = models.CharField(max_length=100)
permissions = models.CharField(max_length=10)
def __unicode__(self):
return self.user
def save(self,*args,**kwargs):
self.passwd = hashlib.sha1(self.passwd+self.user).hexdigest()
super(User,self).save(*args,**kwargs)
当然,这个也可以直接在views.py中进行加密处理,但是牛人说了,在MVC模式下,数据处理应该交给models处理。
以上是 django怎么对密码加密[Django框架] 的全部内容, 来源链接: utcz.com/z/539918.html