django注册与登录问题?小白求教!
<p><p>问题:注册的账号无法登陆,创建的超级管理员账号可以登录,请教是什么问题? 使用Django自带的认证,create_user创建账号后 authenticate无法认证</p></p>
代码如下 注册 class RegisterView(View):
def get(self, request): return render(request, 'register.html') def post(self, request): # 接受数据 user_name = request.POST.get('user_name') password = request.POST.get('pwd') cpwd = request.POST.get('cpwd') email = request.POST.get('email') allow = request.POST.get('allow') # 数据校验 # 是否数据完整 if not all([user_name, password, cpwd, email]): return render(request, 'register.html', {'errmsg': '数据不完整'}) # 邮箱是否正确 result = re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email) if not result: return render(request, 'register.html', {'errmsg': '邮箱错误'}) # 密码与重复密码是否一致 if password != cpwd: return render(request, 'register.html', {'errmsg': '两次密码不一致'}) # 是否同意协议 if allow != 'on': return render(request, 'register.html', {'errmsg': '请统一协议'}) # 用户名是否存在 try: user = User.objects.get(username=user_name) except User.DoesNotExist: user = None if user: return render(request, 'register.html', {'errmsg': '用户名已存在'}) #业务处理 user = User.objects.create_user(username=user_name, email=email, password=password) user.is_active = 0 user.save() #加密文件 serializer = Serializer(settings.SECRET_KEY, 3600) info = {'user_id': user.id} token = serializer.dumps(info) token = token.decode() # url = 'http://127.0.0.1/user/active/'+token.decode() #发邮件 send_register_active_email(email, user_name, token) # 返回应答 return redirect(reverse('goods:index'))
登陆
class LoginView(View):
def get(self, request): #是否记录用户名 if request.COOKIES.get('user_name'): #获取用户名和记住状态 user_name = request.COOKIES.get('user_name') checked = 'checked' else: user_name = '' checked = '' return render(request, 'login.html', {'user_name':user_name, 'checked':checked}) def post(self, request): #获取数据 username = request.POST.get('username') password = request.POST.get('pwd') #校验数据 if not all([password, password]): return render(request, 'login.html', {'errmsg': '数据不完整'}) #1.验证手机号密码是否正确 user = authenticate(username=username, password=password) if user is not None: if user.is_active: #业务处理 #登陆用户 login(request, user) #是否记住用户名 response = redirect(reverse('goods:index')) remember = request.POST.get('remember') if remember == 'on': #记住用户名 response.set_cookie('user_name', username, 7* 24 * 3600) else: #删除cookie response.delete_cookie('user_name') return response else: return render(request, 'login.html', {'errmsg': '账号未激活'}) else: return render(request, 'login.html', {'errmsg': '账号或密码错误'})
评论 1
你注册时,把用户的默认active设置为0,然后你登陆的时候需要active为1,所以注册的登陆不了。