def login(request): """username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(request, username=username, password=password) # 发送此请求的网站 referer = request.META.get('HTTP_REFERER', reverse('home')) if user is not None: auth.login(request, user) # 跳转到首页 return redirect(referer) else: return render(request, 'error.html', {'message': '用户名或密码不正确', 'redirect_to': referer})""" if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): user = login_form.cleaned_data.get('user') auth.login(request, user) # 跳转到来源页 return redirect(request.GET.get('from', reverse('home'))) else: login_form = LoginForm() context = {'login_form': login_form} return render(request, 'user/login.html', context)
def user_login(request): if request.method == 'GET': lform = LoginForm() return render(request, '../../Web/templates/login.html', context={'form': lform}) # else: # lform = LoginForm(request.POST) # if lform.is_valid(): # data = lform.cleaned_data # user = User.objects.filter(username=data.get('username')).first() # # # password = lform.cleaned_data.get('password') # # user = User.objects.filter(username=username).first() # flag = check_password(data.get('password'), user.password) # if user and user.is_active: # flag = check_password(data.get('password'), user.password) # if flag: # # token 令牌 # # uid = uuid.uuid4() # # token = str(uid).replace('-', '') # # print("++++++++>token :", token) # # cache.set(token, user, timeout=60 * 30) # # # 创建response对象 # # request.session['username'] = username # # return redirect('user:index', context={'form': lform}) # # return HttpResponseRedirect('/') # # return render(request, '../../Web/templates/login.html', context={'form': lform, 'msg': '用户名或者密码有误!'}) # username = lform.cleaned_data.get('username') # request.session['username'] = username # return HttpResponseRedirect('/') # else: # return render(request, '../../Web/templates/login.html', context={'form': lform, 'msg': '请检查用户名或者用户没有激活!'}) # return render(request, '../../Web/templates/login.html', context={'form': lform, 'msg': '用户名或者密码有误!'}) else: lform = LoginForm(request.POST) if lform.is_valid(): username = lform.cleaned_data.get('username') password = lform.cleaned_data.get('password') user = User.objects.filter(username=username).first() flag = check_password(password, user.password) if flag: # 保存session信息 username = lform.cleaned_data.get('username') request.session['username'] = username return HttpResponseRedirect('/') else: return render(request, '../../Web/templates/login.html', context={ 'form': lform, 'msg': '请检查用户名或者用户没有激活!' }) return render(request, '../../Web/templates/login.html', context={ 'form': lform, 'msg': '用户名或者密码有误!' })
def loginView(request): context = {} user = request.user if user.is_authenticated: return HttpResponseRedirect(reverse('home')) if request.POST: form = LoginForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(username=email, password=password) if user: login(request, user) return HttpResponseRedirect(reverse('home')) else: form = LoginForm() context['form'] = form return render(request, "user/login.html", context)
def user_login(request): if request.method == 'GET': lform = LoginForm() return render(request, 'login.html', context={'form': lform}) else: lform = LoginForm(request.POST) if lform.is_valid(): data = lform.cleaned_data user = User.objects.filter(username=data.get('username')).first() if user and user.is_active: flag = check_password(data.get('password'), user.password) if flag: # token 令牌 uid = uuid.uuid4() token = str(uid).replace('-', '') print("++++++++>token :", token) cache.set(token, user, timeout=60 * 30) # 创建response对象 res = HttpResponse('用户登录成功') res.set_cookie('token_', token) return res else: return render(request, 'login.html', context={ 'form': lform, 'msg': '请检查用户名或者用户没有激活!' }) return render(request, 'login.html', context={ 'form': lform, 'msg': '用户名或者密码有误!' })
def login_view(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): user = authenticate(username=form.cleaned_data["username"], password=form.cleaned_data["password"]) if user is not None and user.is_confirmed != "NOT_CONFIRMED": login(request, user) return redirect(reverse('root')) else: return render( request, "login.html", { "form": form, "errors": [ "Incorrect login or password or you need to confirm your account" ] }) else: return render(request, "login.html", {"form": form}) else: if request.user.is_authenticated: return redirect(reverse('profile')) form = LoginForm() return render(request, "login.html", {"form": form})
def login(request): if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): identifier = login_form.cleaned_data['identifier'] password = login_form.cleaned_data['password'] user = authenticate(request, username=identifier, password=password) if user != None: login_user(request, user) return redirect('main-page') else: context_dict = { 'form': login_form, 'invalid_credentials': True } return render(request, 'user/login.html', context_dict) else: context_dict = {'form': login_form, 'invalid_credentials': True} return render(request, 'user/login.html', context_dict) else: login_form = LoginForm() context_dict = {'form': login_form, 'invalid_credentials': False} return render(request, 'user/login.html', context_dict)
def login_account(request): try: args={} form = LoginForm() if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data username = cd['username'] password = cd['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: # update last login in database result = User.objects.filter(username=username).update(last_login=datetime.datetime.now()) login(request, user) #Django buildin login method # request.session['bookserviceUser'] = username # response = HttpResponse() # response.set_cookie('bookserviceLogin', 'True') return HttpResponseRedirect('/test/') else: messages.add_message(request, messages.INFO, 'This account has been disabled.') else: messages.add_message(request, messages.INFO, 'Invalid Username and Password') else: args['form'] = form return render(request, 'user/login.html', args) else: return render(request, 'user/login.html', {'form':form}) except: messages.add_message(request, messages.ERROR, sys.exc_info()[1]) return render(request, 'user/login.html', {'form':form})
def login_view(request): if request.method == "POST": login_form = LoginForm(request.POST) if login_form.is_valid(): cd = login_form.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) if user: # request.session["info"] = "infomation" '''用户登陆后,Django会自动调用默认的session应用, 将用户的id存至session中,通常情况下,login与authenticate 配合使用''' login(request, user) # request.session.set_expiry(0) # 关闭浏览器自动退出登录 return HttpResponseRedirect(reverse('file:file')) else: return render( request, 'user/login.html', { "form": login_form, 'status': 'ERROR Incorrect username or password' }) else: return render(request, 'user/login.html', { "form": login_form, 'status': '输入不合法' }) elif request.method == "GET": if request.user.is_authenticated: return HttpResponseRedirect(reverse('file:file')) else: login_form = LoginForm() return render(request, 'user/login.html', {"form": login_form})
def loginUser(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): messages.success(request, 'Successfully Logged in') username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) login(request, user) return redirect("index") else: context = { "form": form } return render(request, "login.html", context) else: form = LoginForm() context = { "form": form } return render(request, "login.html", context)
def user_login(request): context = {} if request.method == "GET": form = LoginForm() context['form'] = form return render(request, "user/login.html", context=context) else: form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") # 方式一: 没有继承AbstractUser的用户使用这种方法 """ # 进行数据库查询 user = UserProfile.objects.filter(username=username).first() # 判断密码是否正确 flag = check_password(password, user.password) if flag: # 保存登录的session信息 request.session['username'] = username # 跳转到主页 """ context.update(get_index_info()) context["msg"] = 'loginSuccess' # 方式二: 继承了AbstractUser的用户 可以使用 user = authenticate(username=username, password=password) if user: login(request, user) # 将用户对象保存到底层的request中(session) return render(request, "index.html", context=context) return render(request, "user/login.html", context={ "form": form, "msg": "login_error" })
def user_login(request): '''username = request.POST.get('username','') password = request.POST.get('password','') user = authenticate(request, username=username, password=password) #current_http = request.META.get('HTTP_REFERER','/') #获得当前网址,'/'为默认的网址,首页 current_http = request.META.get('HTTP_REFERER', reverse('home')) #反向解析home获得home的网址 if user is not None: login(request, user) # Redirect to a success page. return redirect(current_http) else: # Return an 'invalid login' error message. return render(request,'blog/error.html',{'messege':'用户名或密码不正确'})''' if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): user = login_form.cleaned_data['user'] login(request, user) # Redirect to a success page. return redirect(request.GET.get('from', reverse('home'))) else: login_form = LoginForm() context = {} context['login_form'] = login_form return render(request, 'login.html', context)
def login(request): # Creamos el formulario de autenticación vacío form = LoginForm() if request.method == "POST": # Añadimos los datos recibidos al formulario form = LoginForm(data=request.POST) # Si el formulario es válido... if form.is_valid(): # Recuperamos las credenciales validadas username = form.cleaned_data['username'] password = form.cleaned_data['password'] # Verificamos las credenciales del usuario user = authenticate(username=username, password=password) # Si existe un usuario con ese nombre y contraseña if user is not None: # Hacemos el login manualmente do_login(request, user) # Y le redireccionamos a la portada return redirect('/') form.add_error('username','El nombre de usuario o la contraseña no existen') # Si llegamos al final renderizamos el formulario return render(request, "login.html", {'form': form})
def login(): if request.method == 'POST': form = LoginForm(request.form) if form.validate(): login_user(form.user, remember=form.remember_me.data) flash('Successfully logged in as %s' % form.user.email, 'success') return redirect(request.args.get('next') or url_for('homepage')) else: form = LoginForm() return render_template('user/login.html', form=form)
def login(request): if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): user = login_form.cleaned_data['user'] auth.login(request, user) return redirect(request.GET.get('from', reverse('home'))) else: login_form = LoginForm() return render(request, 'login/login.html', {'login_form': login_form})
def login(request): content = {} if request.method == "POST": login_form = LoginForm(request.POST) if login_form.is_valid(): user = login_form.cleaned_data['user'] auth.login(request, user) return redirect(request.GET.get('from', reverse('home'))) else: login_form = LoginForm() content['login_form'] = login_form return render(request, 'user/login.html', content)
def login(request): if request.method == 'POST': # 加判断login这个方法是打开登录页面的处理,还是提交登录数据的请求。相当于2个方法合并到一个来。 login_form = LoginForm(request.POST) # 将post传来的数据实例化成表单 if login_form.is_valid(): user = login_form.cleaned_data["user"] auth.login(request, user) return redirect(request.GET.get("from", reverse('home'))) else: login_form = LoginForm() # request方法不是POST context = {} # if分支的共有部分,都会执行以下代码。 context['login_form'] = login_form return render(request, 'login.html', context)
def login(request): if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): user = login_form.cleaned_data['user'] auth.login(request, user) return redirect( reverse('home')) else: login_form = LoginForm() context = {} context['login_form'] = login_form return render(request, 'templates_user/login.html', context)
def login(request): if request.method == "POST": login_form = LoginForm(request.POST) if login_form.is_valid(): user = login_form.cleaned_data['user'] auth.login(request, user) return redirect( request.GET.get('from', reverse('home')).split('?from=')[-1]) else: login_form = LoginForm() context = { 'login_form': login_form, } return render(request, 'user/login.html', context)
def Login(request): if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): user = login_form.cleaned_data['user'] login(request, user) return redirect(request.GET.get('from')) else: login_form = LoginForm() context = { 'login_form': login_form } return render(request, 'user/login.html', context)
def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): user_email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = authenticate(email=user_email, password=password) if user: login(request, user) return redirect('index') return render(request, 'login.html', {'form': form}) else: form = LoginForm() return render(request, 'login.html', {'form': form})
def login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): user = auth.authenticate(username=form.username, password=form.password) if user: auth.login(request, user) return redirect('index') form = LoginForm() context = { 'form': form, } return render(request, 'user/login.html', context)
def login(request): if request.method == 'POST': form = LoginForm(request.POST) username = form.data['username'] password = form.data['password'] student = Student.objects.all().filter(username = username).filter(password = password) if form.is_valid(): if len(student)==0 : return render(request, 'student_login.html', {'form': form}) else: request.session['username'] = username return HttpResponseRedirect('/student') else: form = LoginForm() return render(request, 'student_login.html', {'form': form})
def login(request): if request.method == 'POST': form = LoginForm(request.POST) username = form.data['username'] password = form.data['password'] instructor = Instructor.objects.all().filter(username = username).filter(password = password) # user = Instructor.authenticate(request, username=username, password=password) if form.is_valid(): if len(instructor)==0 : return render(request, 'instructor_login.html', {'form': form}) else: request.session['username'] = username return HttpResponseRedirect('/instructor') else: form = LoginForm() return render(request, 'instructor_login.html', {'form': form})
def user_login(request): if request.method == 'GET': return render(request, 'user/login.html') else: lform = LoginForm(request.POST) if lform.is_valid(): username = lform.cleaned_data.get('username') password = lform.cleaned_data.get('password') #进行数据库的查询 user = UserProfile.objects.filter(username=username).first() # if user: # flag=check_password(password,user.password) # if flag: # # 保存session信息 # request.session['username']=username #方式二 前提是继承了AbstractUser user = authenticate(username=username, password=password) if user: print(user) res = login(request, user) # # 将用户对象保存在底层的request中 (session) print(res) return redirect(reverse('index')) # return render(request, 'user/login.html', context={'errors': lform.errors})
def login(): form = LoginForm() error = None if request.method == 'GET' and request.args.get('next'): session['next'] = request.args.get('next') if form.validate_on_submit(): user = User.objects.filter(username=form.username.data).first() if user: if bcrypt.hashpw(form.password.data.encode('utf-8'), user.password.encode( 'utf-8')) == user.password.encode('utf-8'): session['username'] = form.username.data if 'next' in session: next = session.get('next') session.pop('next') return redirect(next) else: message = 'Login efetuado com sucesso.' return redirect( url_for('user_app.profile', username=user.username)) else: user = None if not user: error = 'Senha ou nome de usuário incorreto' return render_template('user/login.html', form=form, error=error)
def login(): form = LoginForm() error = None if request.method == 'GET' and request.args.get('next'): session['next'] = request.args.get('next') if form.validate_on_submit(): user = User.objects.filter( username=form.username.data ).first() if user: if bcrypt.hashpw(form.password.data, user.password) == user.password: session['username'] = form.username.data if 'next' in session: next = session.get('next') session.pop('next') return redirect(next) else: return 'User logged in' else: user = None if not user: error = 'Incorrect credentials' return render_template('user/login.html', form=form, error=error)
def user_login(request): context = dict() form = LoginForm(request.POST or None) context["form"] = form if form.is_valid(): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") # if username is not exists throw and error to user try: username = User.objects.get(email=email).username except User.DoesNotExist: messages.info(request, "Username is wrong.") return render(request, "user/login.html", context) # check username and password are correct user = authenticate(request, username=username, password=password) if user is None: messages.info(request, "Username or password is wrong") return render(request, "user/login.html", context) else: messages.success(request, "You have successfully logged in.") # start new session for user login(request, user) return redirect("index") return render(request, "user/login.html", context)
def blog_detail(request, blog_id): blog = get_object_or_404(Blog, pk=blog_id) # 浏览器再次刷新时不会更新阅读数 read_cookie_key = ReadStatistics(request, blog) blog_content_type = ContentType.objects.get_for_model(blog) comments = Comment.objects.filter(content_type=blog_content_type, object_id=blog.pk, parent=None) # 支持markdown语法 config = { 'codehilite': { 'use_pygments': False, 'css_class': 'prettyprint linenums', } } # strip_html = re.sub('<[^<]+?>', '', blog.content) blog.body = markdown.markdown(blog.content, extensions=['codehilite'], extension_configs=config) data = { "content_type": blog_content_type.model, "object_id": blog_id, "reply_comment_id": 0, } context = { "blog": blog, "previous_blog": Blog.objects.filter(create_time__gt=blog.create_time).last(), "next_blog": Blog.objects.filter(create_time__lt=blog.create_time).first(), "comments": comments.order_by("-comment_time"), "comments_count": Comment.objects.filter(content_type=blog_content_type, object_id=blog.pk).count(), "comment_form": CommentForm(initial=data), "login_form": LoginForm() } response = render(request, "blog/blog_detail.html", context) response.set_cookie(read_cookie_key, "true") # 设置cookie return response
def login(): """The login function allow the user entry into the application depending on whether their password is correct or not. """ form = LoginForm() error = None _set_next_variable_to_session_if_found() if form.validate_on_submit(): user = User.objects.filter(email=form.email.data).first() if not user: error = errors.INCORRECT_CREDENTIALS else: if not _is_email_address_confirmed(user): error = errors.EMAIL_VERIFICATION elif Password.check_password(form.password.data, user.password): Session.add(session_name="username", session_value=user.username.lower()) return redirect(url_for("home_app.home")) else: error = errors.INCORRECT_CREDENTIALS return render_template("users/login/login.html", error=error, form=form)
def blog_detail(request, blog_pk): context = {} # pk = urls.py中对应的path名称 blog = get_object_or_404(Blog, pk=blog_pk) # 记录阅读量 read_cookie_key = read_statistics_once_read(request, blog) # 评论对象 blog_content_type = ContentType.objects.get_for_model(blog) comments = Comment.objects.filter(content_type=blog_content_type, object_id=blog.pk, parent=None) context['blog'] = blog context['user'] = request.user context['comments'] = comments.order_by('-comment_time') # form表单 context['comment_form'] = CommentForm( initial={ 'content_type': blog_content_type.model, 'object_id': blog_pk, 'reply_comment_id': 0 }) context['login_form'] = LoginForm() # 获取比当前blog创建时间晚的博客集合中最后一条 context['previous_blog'] = Blog.objects.filter( created_time__gt=blog.created_time).last() # 获取比当前blog创建时间早的博客集合中第一条 context['next_blog'] = Blog.objects.filter( created_time__lt=blog.created_time).first() # 设置cookie用于记录阅读量 response = render(request, 'blog/blog_detail.html', context) response.set_cookie(read_cookie_key, 'true') return response