예제 #1
0
파일: views.py 프로젝트: JD99/mysite1
def login_views(request):
    if not request.user.is_authenticated():
        if request.method == 'POST':
            form = LoginForm(request.POST)
            if form.is_valid():
                if form.get_user():
                    login(request, form.get_user())
                    return HttpResponseRedirect('/')
        else:
            form = LoginForm()
        return render_to_response('blog/api_login.html', {'form': form},context_instance=RequestContext(request))
    else:
        #синхронизация я с бд
        #sync_mail_mailtag(request)
        #количество страниц обработка
        data_count = Mail.objects.all().count()
        max_page = data_count / mail_page
        max_page=int(ceil(max_page))
        #категории для фильтра
        all_filtr = Tags.objects.all()
        #данные из бд
        data = Mail.objects.all()
        data = data.order_by('-mail_numb')
        #разбиение на страницы
        paginator = Paginator(data, int(mail_page))
        page1 = paginator.page(1)   

        return render_to_response('blog/api_index.html', {"data": page1.object_list, "page": '1', "domain_name": domain_name, 'max_page': max_page, 'all_filtr': all_filtr,'mail_page':int(mail_page),'data_count':data_count,},context_instance=RequestContext(request))
예제 #2
0
파일: views.py 프로젝트: mulnz/flask-blog
def login_view():
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        user = load_user(form.data['shortname'])
        login_user(user)
        return redirect(url_for('index_view'))
    return render_template_with_models('login.html', form=form)
예제 #3
0
def login():

    login_form = LoginForm()

    if login_form.validate_on_submit():

        # read values from the login wtform
        username = login_form.username.data
        password = login_form.password.data

        user = User.objects(username=username).first()

        # if user  != None:
        # check if credentials are valid
        if user and user.authenticate(username, password):
            # store the user ID in the session
            session['uid'] = str(user.id)
            session['username'] = user.username
            session['firstname'] = user.first_name
            session['lastname'] = user.last_name
            session['biography'] = user.biography
            session['role'] = user.role

        return redirect("/profile")

    # render the login template
    return render_template('login/login.html', form=login_form)
예제 #4
0
def login(request, template="login.html"):
    if request.method == "POST":
        if request.POST["type"] == "register":
            register_form = RegisterationForm(request.POST)
            login_form = AuthenticationForm()
            if register_form.is_valid():
                user = register_form.save(commit=False)
                user.email = register_form.cleaned_data.get("email")
                user.save()
                profile = Profile.objects.create(user=user)
                send_mail_with_template(u"Selamlar efendim!", user.email, "mails/wellcome.html", {"user": user})
                send_mail_with_template(u"Yeni üye kaydı!", settings.MY_MAIL, "mails/wellcome.html", {"user": user})
                user.backend = "django.contrib.auth.backends.ModelBackend"
                login_func(request, user)
                return redirect("home")
        else:
            login_form = AuthenticationForm(data=request.POST)
            register_form = RegisterationForm()
            if login_form.is_valid():
                login_func(request, login_form.get_user())
                return redirect("home")
    else:
        register_form = RegisterationForm()
        login_form = AuthenticationForm()

    ctx = {"register_form": register_form, "login_form": login_form}

    return render(request, template, ctx)
예제 #5
0
파일: views.py 프로젝트: xxxt/blog
def login(request):
    """用户登录"""
    hint = ''
    backurl = request.GET.get('backurl', 'blog:index')
    if request.method == 'POST':
        backurl = request.POST['backurl']
        form = LoginForm(request.POST)
        if form.is_valid():
            code_from_session = request.session.get('captcha_code')
            code_from_user = form.cleaned_data['code']
            if code_from_session.lower() == code_from_user.lower():
                username = form.cleaned_data['username']
                password = form.cleaned_data['password']
                user = User.objects.filter(username=username,
                                           password=password).first()
                if user:
                    request.session['userid'] = user.no
                    request.session['username'] = user.username
                    return redirect(backurl)
                else:
                    hint = '用户名或密码错误'
            else:
                hint = '请输入正确的验证码'
        else:
            hint = '请输入有效的登录信息'
    return render(request, 'blog/login.html', {
        'hint': hint,
        'backurl': backurl
    })
예제 #6
0
def do_login(request):
    try:
        if request.method == 'POST':
            login_form = LoginForm(request.POST)
            if login_form.is_valid():
                # 登录
                username = login_form.cleaned_data['username']
                password = login_form.cleaned_data['password']
                user = authenticate(username=username, password=password)
                if user is not None:
                    user.backend = 'django.contrib.auth.backends.ModelBackend'  # 指定默认登录验证方式
                    login(request, user)
                else:
                    return render(request, 'failure.html',
                                  {'reason': '登录验证失败'})
                return redirect(request.POST.get('source_url'))
            else:
                return render(request, 'failure.html',
                              {'reason': login_form.errors})
        else:
            login_form = LoginForm()
    except Exception as e:
        logger.error(e)

    return render(request, 'login.html', locals())
예제 #7
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.user.data).first()
        if user:
            if try_login(user, str(form.password.data)):
                flash('Logged in successfully!', 'success')
                log.info("User %s logged in", user)
                login_user(user, remember=form.remember_me.data)
                return redirect(request.args.get("next") or url_for("index"))
            else:
                flash('Log in Error', 'danger')
                log.warn("Log in attempt to '%s' from IP %s",
                         user,
                         request.remote_addr)
                form.errors['password'] = [u"Incorrect Password"]
        else:
            log.warn("Log in attempt to '%s' from IP %s",
                     form.user.data,
                     request.remote_addr)
            flash('User not found!', 'danger')
            form.errors['user'] = [u"User not found"]
    return render_template('login.html',
                           title="Log In",
                           form=form)
예제 #8
0
def Login(request):
    '''
	用户登录界面逻辑实现
	author:陈思齐
	:param request:
	:return:
	'''
    context = {}
    errors = ''
    if request.method == "GET":
        form = LoginForm
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            user = authenticate(username=email, password=password)
            if user and user.is_active:
                login(request, user)
                if request.POST["referer"] and 'register' not in request.POST[
                        "referer"]:
                    return redirect(request.POST["referer"])
                else:
                    return redirect(to='home')

    if "HTTP_REFERER" in request.META:
        context["referer"] = request.META["HTTP_REFERER"]
    else:
        context["referer"] = ""
    context['form'] = form
    context['errors'] = errors
    return render(request, "login.html", context)
예제 #9
0
def login(request,template):
	if request.is_ajax():
		if request.method=="POST":
			if 'username' in request.POST and 'password' in request.POST:
				username=request.POST['username']
				password=request.POST['password']

				form=LoginForm({'username':username,'password':password})
				if form.is_valid():
					#return JsonResponse({'data':True})
					username=form.cleaned_data['username']
					password=form.cleaned_data['password']
					#return JsonResponse({'data':True})
					data=list(Ouser.objects.filter(username=username,password=password).values('id','username','nickname','img'))
					if data:
						#存储session
						data[0]['img']=Img.objects.filter(id=9).values('name')[0]['name']
						request.session[ip_str(request.META['REMOTE_ADDR'])]=data[0]
						#data[0]['username']
						return JsonResponse({'data':data[0]})
					else:
						return JsonResponse({'data':False})

			elif 'del' in request.POST:
				del request.session[ip_str(request.META['REMOTE_ADDR'])]
				return JsonResponse({'data':True})
	else:
		return render_to_response(template)
예제 #10
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        flash('Login requested for user {}, remember_me={}'.format(
            form.username.data, form.remember_me.data))
        return redirect(url_for('index'))

    return render_template('login.html', title='Sign In', form=form)
예제 #11
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        login_user(user)
        return redirect(url_for('admin.blog_manage'))
    else:
        return render_template('login.html', form=form)
예제 #12
0
def login(request: HttpRequest):
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect("/blog/")
    else:
        form = LoginForm()

    return render(request, "blog/login.html", {"form": form})
예제 #13
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.email.data == '*****@*****.**' and form.password.data == 'password':
            flash('You have been logged in', 'success')
            return redirect(url_for('homepage'))
        else:
            flash('Login failed. Please enter valid details', 'danger')
    return render_template('login.html', title='Login', form=form)
def login_function_base_view(request):
	if request.method == 'GET':
		form = LoginForm()
		return render(request, 'login.html', {'form': form})
	else:
		form = LoginForm(request.POST)
		if form.is_valid():
			return redirect('/products')
		else:
			return render(request, 'login.html', {'form': form})
예제 #15
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.email.data == '*****@*****.**' and form.password.data == 'password':
            flash("You are now logged in!", 'success')
            return redirect(url_for('home'))
        else:
            flash("Login unsuccessful, please check email and password!" ,'danger')
        return redirect(url_for('login'))
    return render_template("login.html", title="Login", form=form)
예제 #16
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.email.data == "*****@*****.**" and form.password.data == "start":
            flash(f"You have been logged in!", "success")
            return redirect(url_for("home"))
        else:
            flash("Login Unsuccessful. Please check username and password",
                  "danger")
    return render_template("login.html", title="Login", form=form)
예제 #17
0
def login_view():
    """
    Renders a login page and redirects to the index on completion
    """
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        user = get_user(form.data['shortname'])
        login_user(user)
        return redirect(url_for('admin.index'))
    return render_template_with_models('login.html', form=form)
예제 #18
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.email.data == '*****@*****.**' and form.password.data == 'password':
            flash('You have been logged in!', 'success')
            return redirect(url_for('home'))
        else:
            flash('Login Unsuccessful. Please check username and password',
                  'danger')
    return render_template('login.html', title='Login', form=form)
예제 #19
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.email.data == '*****@*****.**' \
                and form.password.data == 'pass':
            flash('You logged in', 'success')
            return redirect(url_for('home'))
        else:
            flash('login unseccess', 'danger')
    return render_template('login.html', title='Login', form=form)
예제 #20
0
def login_view():
    """
    Renders a login page and redirects to the index on completion
    """
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        user = get_user(form.data['shortname'])
        login_user(user)
        return redirect(url_for('admin.index'))
    return render_template_with_models('login.html', form=form)
예제 #21
0
def login_view(request):  # Logins in user if request is valid.
    if request.user.is_authenticated:
        return redirect(reverse('show_all'))

    if request.method == 'POST':
        form = LoginForm(request.POST)

        if form.is_valid():
            username = form.cleaned_data['username']
            pw = form.cleaned_data['password']
            user = authenticate(username=username, password=pw)

            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect(reverse('show_all'))
                else:
                    form.add_error('username',
                                   'This account has been disabled.')
            else:
                form.add_error('username', 'Login failed')
    else:
        form = LoginForm()

    return render(request, 'registration/login.html', {'form': form})
예제 #22
0
파일: routes.py 프로젝트: Hadiaj448/Amazon
def login():
    form=LoginForm()
    if form.validate_on_submit():
        user=User.query.filter_by(email=form.email.data,password=form.password.data).first()
        if user:
            login_user(user)
            flash(f'Welcome You Successfully loged in','success')
            return redirect(url_for('index'))
        else:
            flash(f'Login Unsuccessfull Try again','danger')
    return render_template('login.html',form=form,title='Login')
예제 #23
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = Users.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user)
            flash('Logged in successfully! ')
            return redirect(url_for('home'))
        else:
            flash('Invalid email address or password.')
    return render_template('login.html', title='Login', form=form)
예제 #24
0
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('blog:index'))
    else:
        login_form = LoginForm()
    context = {'login_form': login_form}
    return render(request, 'blog/login.html', context)
예제 #25
0
def login(request):
    form = LoginForm(request.POST)
    context = {'form': form}
    if form.is_valid():
        username = request.POST["username"]
        password = request.POST["password"]
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            auth.login(request, user)
            return redirect('home')
    return render(request, 'blog/login.html', context)
예제 #26
0
def myaccount():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user)
            flash("You have succssfully logged in")
            return redirect(url_for("home"))
        else:
            flash("Unsuccessful, kindly check your details")
    return render_template("myaccount.html", title="Login", form=form)
예제 #27
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user_attempt = User.query.filter_by(email=form.email.data).first()
        if user_attempt and user_attempt.check_password(form.password.data):
            login_user(user_attempt)
            flash(f'Success! You are logged in as {user_attempt.username}', category='success')
            return redirect(url_for('blogs'))
        else:
            flash("Username and Password are not match!", category='danger')
    return render_template('login.html', form=form)
예제 #28
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('homepage'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('username e password non combaciano!')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        return redirect(url_for('homepage'))
    return render_template("login.html", form=form)
예제 #29
0
 def post(self, request):
     form = LoginForm(data=request.POST)
     if form.is_valid():
         user = authenticate(
             request,
             username=form.cleaned_data["username"],
             password=form.cleaned_data["password"],
         )
         if user:
             login(request, user)
             return HttpResponseRedirect(reverse("posts"))
     return render(request, "blog/login_page.html", {"login_form": form})
예제 #30
0
def login():
    if g.user is not None and g.user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        session['remember_me'] = form.remember_me.data
        return open_id.try_login(form.openid.data,
                                 ask_for=['nickname', 'email'])
    return render_template('login.html',
                           title='Sign In',
                           form=form,
                           providers=app.config['OPENID_PROVIDERS'])
예제 #31
0
def login():
  """ Login page, shows the login form """
  form = LoginForm()

  if form.validate_on_submit():
      user = User.query.filter_by(username=form.username.data).one()
      login_user(user)

      flash("You've been logged in", "success")
      return redirect(url_for(".index"))

  return render_template("login.html", form=form)
예제 #32
0
파일: views.py 프로젝트: Marilyna/blog
def sign_in(request):
    nexturl = request.GET.get('next') or 'index'
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            login(request, form.user)
            return redirect(request.POST.get('next'))
    else:
        form = LoginForm()

    context = {'form': form, 'next': nexturl}
    return render(request, 'login.html', context)
예제 #33
0
def login():
	if current_user.is_authenticated:
		return redirect(url_for('home'))
	form = LoginForm()
	if form.validate_on_submit():
		user = User.query.filter_by(email=form.email.data).first()
		if user and bcrypt.check_password_hash(user.password, form.password.data):
			login_user(user, remember=form.remember.data)
			return redirect(url_for('home'))
		else:
			flash('Login Unsuccessful! Please check email and password', 'danger')
	return render_template("login.html", title = 'Login', form=form)
예제 #34
0
def login():
    """ Login page, shows the login form """
    form = LoginForm()

    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).one()
        login_user(user)

        flash("You've been logged in", "success")
        return redirect(url_for(".index"))

    return render_template("login.html", form=form)
예제 #35
0
def login(request):
	context = RequestContext(request)
	if request.method == 'POST':
		form = LoginForm(request.POST, request.FILES)
		if form.is_valid(): # is the form valid
			form.save(commit=True) # yes and save to db
			return redirect(index)
		else:
			print form.errors  # no, display error to end user
	else:
		form = LoginForm()
	return render_to_response('blog/login.html', {'form': form}, context)
예제 #36
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.email.data == '*****@*****.**' and form.password.data == 'admin@123':
            flash(f'You have been logged in successfully as {form.email.data}',
                  'success')
            return redirect(url_for('home'))
        else:
            flash(
                'Login Unsuccessful! Please Check email and password and try again',
                'danger')
    return render_template('login.html', title='Login', form=form)
예제 #37
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form=LoginForm()
    if form.validate_on_submit():
        user=User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password,form.password.data):
            login_user(user,remember=form.remember.data)
            next_page=request.args.get('next')
            return redirect(next_page) if next_page else redirect(url_for('home'))
        else:
            flash('Login Unsucessful.Please check email and password',category='danger')
    return render_template('login.html',title='Login',form=form)
예제 #38
0
def login():
    form = LoginForm()
    errors = None
    next_url = request.args.get('next')
    if request.method == 'POST':
        if form.validate_on_submit():
            session['logged_in'] = True
            session.permanent = True
            flash('You are now logged in.', 'success')
            return redirect(next_url or url_for('index'))
        else:
            errors = form.errors
    return render_template("login_form.html", form=form, errors=errors)
예제 #39
0
파일: views.py 프로젝트: mcrisan/blog
def user_login():
        form = LoginForm()
        next = request.args.get('next')
        if form.validate_on_submit():
            flash('Successfully logged in as %s' % form.user.username)
            session['user_id'] = form.user.id
            user = User.query.get(form.user.id)
            login_user(user)
            if next != "None":
                return redirect(next)
            else:
                return redirect(url_for('blog.index'))
        return render_template('login.html', form=form)
예제 #40
0
def connexion(request):
    error = False
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
            else:
                error = True
    else:
        form = LoginForm()
    return render(request, 'blog/login.html', locals())
예제 #41
0
def login():
	''' Wraps flask-login's login method. '''
	form = LoginForm(request.form)
	if request.method == 'POST':
		if not form.validate():
			flash('Invalid login information. Please try again.')
		else:
			email, password = request.form['email'], request.form['password']
			if not User_.objects(email=email, password=password):
				flash("Incorrect credentials. Please try again.")
			else:
				admin = User(form.email.data, form.password.data)
				login_user(admin)
				return redirect(url_for('posts.admin'))
	return render_template('login.html', form=form)
예제 #42
0
def login(request):
    if request.method == 'GET':
        return render(request, 'ad/login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            user = auth.authenticate(username=username, password=password)
            if user is not None and user.is_active:
                auth.login(request, user)
                return HttpResponse('success')
            else:
                return HttpResponse('password is wrong')
        else:
            return HttpResponse('user does not exist')
예제 #43
0
def login_u(request):

	if request.method == 'POST':
		uf = LoginForm(request.POST)
		if uf.is_valid():
			username = uf.cleaned_data['username']
			password = uf.cleaned_data['password']
			user = authenticate(username=username,password=password)
			if user:
				# request.session['user'] = user
				login(request, user)
				return HttpResponseRedirect('/index/')
			return HttpResponse('no')
	else:
		uf = LoginForm()
	return render(request,'register.html',{'uf':uf})
예제 #44
0
파일: views.py 프로젝트: SamuelMartens/blog
def home_page(request,option_mes='',page=1):
    #Реализация поиска
    if 'search_input' in request.GET and request.GET['search_input']!='':
        if request.GET.get('search_by')=='all':
            posts=Post.objects.filter(Q(author__username__icontains=request.GET['search_input'])| Q(theme__icontains=request.GET['search_input']))
        elif request.GET.get('search_by')=='theme':
            posts=Post.objects.filter(theme__icontains=request.GET['search_input'])
        else:
             posts=Post.objects.filter(author__username__icontains=request.GET['search_input'])
        if len(posts)==0:
            option_mes='There is no result of this search'
        return render_to_response('base.html',{'option_mes':option_mes,'posts':posts},context_instance=RequestContext(request))
    else:
        posts=Post.objects.all()

    #Реализация счетсчика страниц
    page=int(page)
    page_size=5         #Переменная отвечающая за кол-во постов на одной страничке
    max_view_range=len(posts)//page_size if len(posts)%page_size==0 else len(posts)//page_size+1
    if max_view_range<6:
        view_range=(1,max_view_range+1)
    else:
        view_range=(1,6)          #Отражает диапазон счетчика страниц
    if page>view_range[1] or view_range[1]==(page+1) and max_view_range>6:
        view_range=((page-2),(page+3))
        if view_range[1]>max_view_range:
            view_range=(max_view_range-4,max_view_range+1)
    if page>max_view_range:raise Http404
    view_range=range(*view_range)
    posts=posts[((page-1)*page_size):(page*page_size)]

    #Реализация логина
    if request.method=='POST' and ('log_form' in request.POST) and request.session.test_cookie_worked():
        log_form=LoginForm(request.POST)
        if log_form.is_valid():
            user=log_form.log_in(request)
            if user is None:
                option_mes='Wrong username or password'
            else:
                option_mes='You have succesfully log in!'
        else:
            option_mes='No cookies allowed'
    if 'log_out_form' in request.GET:
        auth.logout(request)
        option_mes='You have loged out'
    request.session.set_test_cookie()
    return render_to_response('base.html',{'option_mes':option_mes,'posts':posts,'view_range':view_range,'current_page':page},context_instance=RequestContext(request))
예제 #45
0
def login(request):
    """
    Do user log in
    """
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            user = auth.authenticate(username=data['user'], password=data['password'])
            if user is not None and user.is_active:
                auth.login(request, user)
                return HttpResponseRedirect('/adminindex/')
            else:
                return render_to_response('login.html', {'form':form}, context_instance=RequestContext(request, processors=[new_blog, blog_group]))
    else:
        form = LoginForm()
    return render_to_response('login.html', {'form':form}, context_instance=RequestContext(request, processors=[new_blog, blog_group]))
예제 #46
0
def login(request):  
    if request.method == 'GET':  
        form = LoginForm()  
        return render_to_response('login.html', RequestContext(request, {'form': form,}))  
    else:  
        form = LoginForm(request.POST)  
        if form.is_valid():  
            username = request.POST.get('username', '')  
            password = request.POST.get('password', '')  
            user = auth.authenticate(username=username, password=password)  
            if user is not None and user.is_active:  
                auth.login(request, user)  
                return render_to_response('admin_bloglist.html', RequestContext(request))  
            else:  
                return render_to_response('login.html', RequestContext(request, {'form': form,'password_is_wrong':True}))  
        else:  
            return render_to_response('login.html', RequestContext(request, {'form': form,}))  
예제 #47
0
파일: views.py 프로젝트: goodking-bq/zblog
def login():
    if g.user is not None and g.user.is_authenticated():
        return redirect(url_for('index'))
    form = LoginForm(request.form)
    if form.validate_on_submit() and request.method == 'POST':
        user = User.user_check(passwd=form.passwd.data, email=form.email.data)
        remember_me = form.remember_me.data
        if user:
            login_user(user, remember=remember_me)
            flash(u'恭喜,登录成功!')
            log = Login_log(email=user.email,
                            ip=request.remote_addr)
            db.session.add(log)
            db.session.commit()
            Blog_info.new_login()
            return redirect(request.args.get("next") or url_for("index"))
        else:
            flash(u'用户名或密码错误')
            return redirect(url_for('login'))
    return render('login.html',
                  title=u'请登陆',
                  form=form)
예제 #48
0
파일: views.py 프로젝트: Look-jie/jie
def do_login(request):
    try:
        if request.method == 'POST':
            login_form = LoginForm(request.POST)
            if login_form.is_valid():
                # 登录
                username = login_form.cleaned_data["username"]
                password = login_form.cleaned_data["password"]
                user = authenticate(username=username, password=password)
                if user is not None:
                    # 指定默认的登录验证方式
                    user.backend = 'django.contrib.auth.backends.ModelBackend'
                    login(request, user)
                else:
                    return render(request, 'failure.html', {'reason': '登录验证失败'})
                return redirect(request.POST.get('source_url'))
            else:
                return render(request, 'failure.html', {'reason': login_form.errors})
        else:
            login_form = LoginForm()
    except Exception as e:
        logger.error(e)
    return render(request, 'login.html', locals())
예제 #49
0
def login_user(request):
	if request.user.is_anonymous():
		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:
					if user.is_active:
						login(request, user)
						return redirect(reverse('index'))
					else:
						messages.add_message(request, messages.ERROR, 
							mark_safe(_('''Account not activated yet, check your
							 email for the validation link. <a href="
							/blog/resend/">Not there? Resend it here!</a>''')))

						return render_to_response('blog/login.html', {'form': form},
						context_instance=RequestContext(request))
				else:
					messages.add_message(request, messages.ERROR, 
					_('Wrong username or password.')) 

					return render_to_response('blog/login.html', {'form': form},
						context_instance=RequestContext(request))
			else:
				return render_to_response('blog/login.html', {'form': form},
						context_instance=RequestContext(request))
		else:
			form = LoginForm()
		
			return render_to_response('blog/login.html', {'form': form},
				context_instance=RequestContext(request))
	else:
		return redirect(reverse('index'))
예제 #50
0
def loginform(request):
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data["username"]
            password = form.cleaned_data["password"]
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    cat = CATEGORY.objects.all()
                    CHOICES = []
                    for c in cat:
                        CHOICES.append((c.id, c.category_name))
                    products_obj = PRODUCT.objects.filter(category_id_id=1, status=1).exclude(owner=request.user.id)
                    products = []
                    for p in products_obj:
                        products.append(p)
                    info_dict = {"products": products, "error": "", "choices": tuple(CHOICES)}
                    return render(request, "blog/products_in_category.html", info_dict)
                # return HttpResponseRedirect(reverse('products_in_category',kwargs={'category_id':1})
                else:
                    msg = "Dear ", user.get_full_name(), ", your account is not active!"
                    form = LoginForm()
                    return render(request, "blog/login.html", {"error": "Invalid Credentials", "form": form})
            else:
                msg = "hello"
                form = LoginForm()
                return render(request, "blog/login.html", {"error": "Invalid Credentials", "form": form})
        else:
            form = LoginForm()
            return render(request, "blog/login.html", {"error": "Invalid Credentials", "form": form})

    elif request.user and request.user.id is not None:
        # msg = 'hell'
        # profile = UserProfile.objects.filter(user_id=request.user.id)
        if UserProfile.objects.filter(user_id=request.user.id).exists():
            msg = "helolo"

        else:
            profile1 = UserProfile.objects.create(user_id=request.user.id)
            profile1.save()
        # profile = UserProfile.objects.create(user_id=request.user.id, card_no='76868768', exp_date=0000-00-00, cvv='111')
        # profile.save();
        return HttpResponseRedirect(reverse("account_management"))
    else:
        form = LoginForm()
        context = RequestContext(request, {"request": request, "user": request.user, "form": form})
        return render_to_response("blog/login.html", context_instance=context)