当前位置: 首页>>代码示例>>Python>>正文


Python AuthenticationForm.is_valid方法代码示例

本文整理汇总了Python中django.contrib.auth.forms.AuthenticationForm.is_valid方法的典型用法代码示例。如果您正苦于以下问题:Python AuthenticationForm.is_valid方法的具体用法?Python AuthenticationForm.is_valid怎么用?Python AuthenticationForm.is_valid使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.contrib.auth.forms.AuthenticationForm的用法示例。


在下文中一共展示了AuthenticationForm.is_valid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: loginajax

# 需要导入模块: from django.contrib.auth.forms import AuthenticationForm [as 别名]
# 或者: from django.contrib.auth.forms.AuthenticationForm import is_valid [as 别名]
def loginajax(request):
    if request.method == "POST":
        form = AuthenticationForm(data=request.POST)
        if request.is_ajax():
            if form.is_valid():
                user = authenticate(username = request.POST['username'],password = request.POST['password'])
                if user is not None:
                    print "ajax true"
                    login(request, user)
                    return HttpResponse('True')
                else:
                    print "ajax false"
                    return HttpResponse('False')      
            else:
                return HttpResponse('False')
        else:
            if form.is_valid():
                print "reg true"
                user = authenticate(username = request.POST['username'],password = request.POST['password'])
                if user is not None:
                    login(request,user)
            else:
                print "reg false"
            

    else:
        form = AuthenticationForm(request)

    return render_to_response(
        'fancyauth/login_ajax.html',
        {
            "form": form
            },
        context_instance=RequestContext(request)
        )
开发者ID:PLOS-Web,项目名称:AI,代码行数:37,代码来源:views.py

示例2: wrapper

# 需要导入模块: from django.contrib.auth.forms import AuthenticationForm [as 别名]
# 或者: from django.contrib.auth.forms.AuthenticationForm import is_valid [as 别名]
    def wrapper(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):

        if Site._meta.installed:
            current_site = Site.objects.get_current()
        else:
            current_site = RequestSite(request)

        if request.method == 'POST':

            # sometimes we won't have made a get request yet (i.e. if we use a
            # form on a different page to login) so if the referer was
            # from our own site skip the cookie check
            referer = request.META.get('HTTP_REFERER', None)
            try:
                referer = referer.split(u'//')[1]
            except AttributeError:
                referer = ''
            cookies = request.session.test_cookie_worked()
            form = AuthenticationForm(request, request.POST)
            form.is_valid()
        else:
            cookies = True
            form = AuthenticationForm(request.POST)

        request.session.set_test_cookie()
        if cookies or referer.startswith(current_site.domain):
            request.session.delete_test_cookie()
            return f(request, template_name, redirect_field_name)

        return render_to_response(template_name, {
            'form': form,
            redirect_field_name: redirect_field_name,
            'site_name': current_site.name,
        }, context_instance=RequestContext(request))
开发者ID:rob-b,项目名称:Jung,代码行数:36,代码来源:decorators.py

示例3: home

# 需要导入模块: from django.contrib.auth.forms import AuthenticationForm [as 别名]
# 或者: from django.contrib.auth.forms.AuthenticationForm import is_valid [as 别名]
def home(request):
    if not request.user.is_anonymous():
        return HttpResponseRedirect('/private')
    if request.method == 'POST':
        # form sent
        authentication_form = AuthenticationForm(data=request.POST)        
        logger.error('RAC is_valid:'+str(authentication_form.is_valid()))
		
        if authentication_form.is_valid():
            #form OK
            usernm = request.POST['username']
            passwd = request.POST['password']
            access = authenticate(username=usernm, password=passwd)
            logger.error('user:'+usernm)
            if access is not None:
                if access.is_active:
                    login(request, access)
                    return HttpResponseRedirect('/private')
                #else:
                    #raise forms.ValidationError(_("This account is not active."))
                    #return render_to_response('noactivo.html', context_instance=RequestContext(request))
            #else:
                #raise forms.ValidationError(_("This user does not exist."))
                #return render_to_response('nousuario.html', context_instance=RequestContext(request))
    else:
        authentication_form = AuthenticationForm()
    return render_to_response('home.html',{'authentication_form':authentication_form}, context_instance=RequestContext(request))
开发者ID:rcorredorj,项目名称:django-website,代码行数:29,代码来源:views.py

示例4: login

# 需要导入模块: from django.contrib.auth.forms import AuthenticationForm [as 别名]
# 或者: from django.contrib.auth.forms.AuthenticationForm import is_valid [as 别名]
def login(request):

    # Si usuario ya está logado, vamos al perfil.
    if request.user.is_authenticated():
        return redirect('profile')

    # Se define el formulario
    form = AuthenticationForm()

    # Debe ser post
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                auth.login(request, user)
                return redirect('home')
            else:
                #return render_to_response('accounts/login.html')
                # Return a 'disabled account' error message
                return redirect('home')
        else:
            form = AuthenticationForm(data=request.POST)
            form.is_valid()

    return render(request, 'accounts/login.html', {'form': form})
开发者ID:guadiabike,项目名称:guadiabike,代码行数:29,代码来源:views.py

示例5: test_password_whitespace_not_stripped

# 需要导入模块: from django.contrib.auth.forms import AuthenticationForm [as 别名]
# 或者: from django.contrib.auth.forms.AuthenticationForm import is_valid [as 别名]
 def test_password_whitespace_not_stripped(self):
     data = {
         'username': 'testuser',
         'password': ' pass ',
     }
     form = AuthenticationForm(None, data)
     form.is_valid()  # Not necessary to have valid credentails for the test.
     self.assertEqual(form.cleaned_data['password'], data['password'])
开发者ID:DAWZayas-Projects,项目名称:TEJEDOR-RETUERTO-ALEJANDRO,代码行数:10,代码来源:test_forms.py

示例6: login

# 需要导入模块: from django.contrib.auth.forms import AuthenticationForm [as 别名]
# 或者: from django.contrib.auth.forms.AuthenticationForm import is_valid [as 别名]
def login(request, template_name="registration/login.html"):
    form = AuthenticationForm()
    if request.method == "POST":
        username = request.POST.get("username", "").lower()
        password = request.POST.get("password", "")
        print "username: %s" % username
        print "password: %s" % password

        """
        import pdb; pdb.set_trace()
        """
        username = request.POST.get("username", "").lower()
        password = request.POST.get("password", "")
        if username and password:
            try:
                user = User.objects.get(username__iexact=username)
            except User.DoesNotExist:
                user = None

            if user:
                print "user exists"
                response = auth_login(request)
                return response
            else:
                print "no such user, create it"
                usercreationform = UserCreationForm({
                    'username': username,
                    'password1': password,
                    'password2': password,
                    })
                print "print creation form is valid", usercreationform.is_valid()
                if usercreationform.is_valid():

                    usercreationform.save()
                    response = auth_login(request)
                    return response
                else:
                    pass
                    print "invald registration, but valid login?"
        else:
            print "invalid login form"
            print "hi"
            form = AuthenticationForm(data=request.POST)
            form.is_valid() # just doing this to get the errors to trigger
            # import pdb; pdb.set_trace()

    # form = AuthenticationForm()
    ctx = dict(form=form)
    print form.errors
    # if form.errors:
    #     messages.error(request, "Oops, we had a problem logging you in. Can you try again?")
    return render_to_response(
        template_name, RequestContext(request, ctx))
开发者ID:ezl,项目名称:miletracker,代码行数:55,代码来源:views.py

示例7: test_auth_form_warns_if_username_does_not_exist

# 需要导入模块: from django.contrib.auth.forms import AuthenticationForm [as 别名]
# 或者: from django.contrib.auth.forms.AuthenticationForm import is_valid [as 别名]
    def test_auth_form_warns_if_username_does_not_exist(self):
        # username doesn't exist yet
        form = AuthenticationForm(None, {
            "username": "foo"
        })
        self.assertFalse(form.is_valid())
        self.assertTrue(form.has_error("username", code="username"))

        make(get_user_model(), username="foo")
        # username does exist now
        form = AuthenticationForm(None, {
            "username": "foo"
        })
        self.assertFalse(form.is_valid())
        self.assertFalse(form.has_error("username", code="username"))
开发者ID:satchamo,项目名称:invoices,代码行数:17,代码来源:tests.py

示例8: login

# 需要导入模块: from django.contrib.auth.forms import AuthenticationForm [as 别名]
# 或者: from django.contrib.auth.forms.AuthenticationForm import is_valid [as 别名]
def login(request):
    '''
    Small wrapper around the django login view
    '''

    context = {}
    if request.REQUEST.get('next'):
        context['next'] = request.REQUEST.get('next')

    # Sane login, with POST
    if request.method == "POST":
        return django_loginview(request,
                            template_name='user/login.html',
                            extra_context=context)
        
    # log in with GET parameters so users can easily get in by scanning a QR code
    elif request.REQUEST.get('get_login'):
        
        form = AuthenticationForm(request, data=request.GET)
        if form.is_valid():

            auth_login(request, form.get_user())
            return HttpResponseRedirect(reverse('oracle:dashboard'))

        
    return django_loginview(request,
                            template_name='user/login.html',
                            extra_context=context)
开发者ID:benallard,项目名称:pk15-orakel,代码行数:30,代码来源:user.py

示例9: login

# 需要导入模块: from django.contrib.auth.forms import AuthenticationForm [as 别名]
# 或者: from django.contrib.auth.forms.AuthenticationForm import is_valid [as 别名]
def login(request):
    c = all_page_infos(request)
    nexturl = request.GET.get("next", "/")
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        form.fields["password"].max_length = 4096
        if form.is_valid():
            user = form.get_user()
            django_contrib_auth_login(request, user)
            logger.info("Logged in user '%s' (%s) a.k.a '%s'", user.username, user.last_name, user.userprofile.aliases)
            if request.user.userprofile.game_pref_fixed or request.session.get("game_pref", 0) == 0:
                # if pref was set explicitely, always set cookie according to profile
                # or if no cookie set, use profiles setting (even if 0)
                request.session["game_pref"] = request.user.userprofile.game_pref
            else:
                # cookie is already set (!=0), overwrite users pref as it's not fixed
                try:
                    request.user.userprofile.game_pref = int(request.session["game_pref"])
                    request.user.userprofile.save()
                except ValueError:
                    # not int, ignore
                    pass
            return HttpResponseRedirect(nexturl)
        else:
            logger.info("login error: %s", form.errors)
    else:
        form = AuthenticationForm()
    c["next"] = nexturl
    c['form'] = form
    form.fields["password"].max_length = 4096
    return render(request, 'login.html', c)
开发者ID:dansan,项目名称:spring-replay-site,代码行数:33,代码来源:views.py

示例10: login_view

# 需要导入模块: from django.contrib.auth.forms import AuthenticationForm [as 别名]
# 或者: from django.contrib.auth.forms.AuthenticationForm import is_valid [as 别名]
def login_view(request):
    # TODO: rethink and rewrite
    next = request.GET.get('next', '')
    if request.method != 'POST':
        form = AuthenticationForm(request)
        return render_to_response('registration/login.html', {'form': form, 'next': next},
            context_instance=RequestContext(request))
    else:
        form = AuthenticationForm(data=request.POST)
        if not form.is_valid():
            return render_to_response('registration/login.html', {'form': form, 'next': next},
                context_instance=RequestContext(request))

    user = authenticate(username=request.POST['username'], password=request.POST['password'])
    if user is not None:
        if user.is_active:
            #Save username in session
            PREFIX = "_user:"
            MAX_TIME = 48*60*60 #48h in seconds
            #Remove entries older than 48h
            for i in request.session.keys():
                if PREFIX in i and (request.session.get(i) + datetime.timedelta(minutes = 2*24*60)) < datetime.datetime.now():
                    request.session.__delitem__(i)
            request.session.__setitem__(PREFIX+user.username, datetime.datetime.now())
            request.session.set_expiry(MAX_TIME)
            login(request, user)
            signals.addActivity.send(sender=None, user_from=user.get_profile(), action="login", game = None, public=False)
            if request.POST.get('next'):
                return HttpResponseRedirect(request.POST.get('next'))
            return redirect(settings.LOGIN_REDIRECT_URL)
    return HttpResponseRedirect("/")
开发者ID:AndreiRO,项目名称:wouso,代码行数:33,代码来源:views.py

示例11: authenticate_user

# 需要导入模块: from django.contrib.auth.forms import AuthenticationForm [as 别名]
# 或者: from django.contrib.auth.forms.AuthenticationForm import is_valid [as 别名]
def authenticate_user(username, password):
    # reuse form-model logic in AuthenticationForm
    auth_dict = {"username": username, "password": password}
    auth_form = AuthenticationForm(None, auth_dict)
    is_valid = auth_form.is_valid()  # just run the validation
    auth_user = auth_form.get_user()
    return auth_user
开发者ID:WhitespaceCrew,项目名称:django-htk,代码行数:9,代码来源:general.py

示例12: loginUsuario

# 需要导入模块: from django.contrib.auth.forms import AuthenticationForm [as 别名]
# 或者: from django.contrib.auth.forms.AuthenticationForm import is_valid [as 别名]
def loginUsuario(request, template_name='user/loginUsuario.html'):
    if not request.user.is_anonymous():
        return redirect('home')
    if request.method == 'POST':
        formulario = AuthenticationForm(None, request.POST or None)
        if formulario.is_valid():
            usuario = request.POST['username']
            clave = request.POST['password']
            acceso = authenticate(username=usuario, password=clave)
            if acceso is not None:
                if acceso.is_active:
                    login(request, acceso)
                    return redirect('home')
                    print 'acceso'
                else:
                    print 'no activo'
                    return redirect('home')
            else:
                print 'no usuario'
                return redirect('home')
        else:
            formulario = AuthenticationForm()
    else:
        formulario = AuthenticationForm()
    return render(request, template_name, locals())
开发者ID:gmunozc,项目名称:HCMFront,代码行数:27,代码来源:views.py

示例13: login

# 需要导入模块: from django.contrib.auth.forms import AuthenticationForm [as 别名]
# 或者: from django.contrib.auth.forms.AuthenticationForm import is_valid [as 别名]
def login(request):
    #messages.debug(request, "Debug!")
    #messages.info(request, "Info!")
    #messages.success(request, "Success!")
    #messages.warning(request, "Warning!")
    #messages.error(request, "Error!")
    
    if request.user.is_authenticated():
        return redirect("/student")
    
    context = {}
    if request.method == "POST":
        form = AuthenticationForm(None, request.POST)
        if form.is_valid():
            user = form.get_user()
            print(user)
            if user.is_active:
                do_login(request, user)
                return redirect("/student")
            else:
                messages.error(request, "Benutzeraccount ist deaktiviert!")
    else:
        form = AuthenticationForm()
    context["form"] = form
    return render(request, "session/login.html", context, context_instance=RequestContext(request))
开发者ID:m0r13,项目名称:abizeitung_django,代码行数:27,代码来源:session.py

示例14: login

# 需要导入模块: from django.contrib.auth.forms import AuthenticationForm [as 别名]
# 或者: from django.contrib.auth.forms.AuthenticationForm import is_valid [as 别名]
def login(request, species_wid=None):
	next = request.REQUEST.get('next', '')
	
	if request.method == "POST":
		form = AuthenticationForm(data=request.POST)
		if form.is_valid():
			auth_login(request, form.get_user())
			
			if request.session.test_cookie_worked():
				request.session.delete_test_cookie()

			return HttpResponseRedirect(next)
	else:
		form = AuthenticationForm(request)

	request.session.set_test_cookie()

	return render_queryset_to_response(
		species_wid = species_wid,
		request = request, 
		templateFile = 'public/login.html', 
		data = {
			'form': form,
			'next': next,
		})
开发者ID:CyanoFactory,项目名称:CyanoFactoryKB,代码行数:27,代码来源:views.py

示例15: login

# 需要导入模块: from django.contrib.auth.forms import AuthenticationForm [as 别名]
# 或者: from django.contrib.auth.forms.AuthenticationForm import is_valid [as 别名]
def login(request):
    username = request.REQUEST.get('username')
    if username:
        userlist = get_user_model().objects.filter(username=username)[:1]
        if len(userlist) > 0:
            user = userlist[0]
            if not user.is_active:
                return getResult(False, u'用户已经停止使用。')
    form = AuthenticationForm(data=request.POST)
    if form.is_valid():


        # Okay, security checks complete. Log the user in.
        auth_login(request, form.get_user())

        if request.session.test_cookie_worked():
            request.session.delete_test_cookie()
        org_num = request.user.person_set.filter(is_action=True).count()
        if org_num == 1:
            request.session['person'] = request.user.paper_set.filter(is_action=True)[0]
            request.session['org'] = request.session['person'].org
        if not request.user.email_active:
            return getResult(True, u'登录成功,请完成邮箱验证', None, 202)
        return getResult(True, u'登录成功', None)
    else:
        return getResult(False, u'用户名密码错误', request.session.session_key, 500)
开发者ID:wangjian2254,项目名称:CalendarOA,代码行数:28,代码来源:views_user.py


注:本文中的django.contrib.auth.forms.AuthenticationForm.is_valid方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。