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


Python forms.AuthenticationForm类代码示例

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


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

示例1: login

def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
	if TEMP_DEBUG_LOGGING:
		TEMP_DEBUG_FILE = open('/tmp/os-debug.log','a')
		TEMP_DEBUG_FILE.write("\nLogin:" + str(datetime.datetime.now()) + "\n")
	
	"Displays the login form and handles the login action."
	if request.method == "POST":
		form = AuthenticationForm(data=request.POST)
		from django.contrib.auth import login
		if form.is_valid():
			user = form.get_user()

			# Check if the user is banned
			user_ob = User.objects.filter(username = user)
			if len(user_ob) != 0:
				if len(BanishedUser.objects.filter(user = user_ob[0])) != 0:
					return json_result({'form_errors': {"__all__":["User is banned"]}})

			login(request, user)
			
			# If this was a visitor, connect to a user
			connect_visitor_to_user(request, user.id)
			
			# Log the login
			create_user_event_log(request, {"log_type": LogUserEvents.login})

			if TEMP_DEBUG_LOGGING:
				TEMP_DEBUG_FILE.write("Login results is user_authenticated?" + str(request.user.is_authenticated()))
				TEMP_DEBUG_FILE.close()
			return json_result({'success' : True, 'sms_can_change_password': get_sms_can_change_password(request.user)})#json_success()
		else:
			if Settings.objects.boolean('SOFT_ENTRY_CODES'):
				c = request.POST.get('entrycode','')
				code_object = EntryCode.objects.filter(code = c)
				if len(code_object) <= 0:
					return json_error('Invalid Entry Code')

				u = User.objects.filter(username = code_object[0].username)

				if len(u) <= 0:
					return json_error('Entry code and user do not match')
					
				if code_object[0].first_login:
					first_login_time = UserData(user = u[0], key = 'first_login', value = time.time())
					first_login_time.save()
					
				code_object[0].first_login = False
				code_object[0].save()
				connect_visitor_to_user(request, u[0].id)
				request.session['user_id'] = u[0].id
				request.session['_auth_user_id'] = u[0].id
				request.session['_auth_user_backend'] = 'opinion.email-auth.EmailOrUsernameModelBackend'
				return json_success()
			# Invalid login
			if TEMP_DEBUG_LOGGING:
				TEMP_DEBUG_FILE.write(json_result({'form_errors': errors_to_dict(form.errors)}).content)
				TEMP_DEBUG_FILE.close()
			return json_result({'form_errors': errors_to_dict(form.errors)})
	else:
		return json_error('Invalid request.')
开发者ID:BerkeleyAutomation,项目名称:mooc-cafe,代码行数:60,代码来源:views.py

示例2: entrar

def entrar(request):
	user = request.user
	ctx = {}

	if request.method == 'GET' and 'next' in request.GET: #miramos si está la variables next para redirección
		ctx['next'] = request.GET['next'] #guardamos la variables next para enviar al template
	#Comprobamos si el usuario está autenticado!
	if user.is_authenticated():
		return redirect( get_url_redir(request) )
	#Si el usuario envía datos por POST para su autenticación
	if request.method == 'POST':
		form = AuthenticationForm(data=request.POST) #usamos el formulario de auth de django
		if form.is_valid(): #si el form es válido obtenemos el usuario y password
			u = form.cleaned_data['username']
			p = form.cleaned_data['password']
			user = authenticate(username=u, password=p) #comprobamos usuario y contraseña
			if user is not None and user.is_active: #si existe y si está activo
				login(request, user) #logueado en las sesion de django
				# dependiendo del depto al q pertenece el user así se redirecionará
				return redirect( get_url_redir(request) )
		else:
			ctx['form'] = form #guardamos el form con los datos resultantes de la validación
			return render(request, 'GestionUser/entrar.html', ctx)

	form = AuthenticationForm() #un formulario sin datos del POST
	ctx['form'] = form #guardamos un form limpio
	return render(request, 'GestionUser/entrar.html', ctx)
开发者ID:cammend,项目名称:SGPC,代码行数:27,代码来源:views.py

示例3: custlogin

def custlogin(request, template_name="custlogin.html"):
    context = {}
    context.update(csrf(request))
    next = None

    try:
        next = request.GET['next']

    except:
        next = ""

    auth_frm = AuthenticationForm(data=request.POST or None)
    context['form'] = auth_frm

    if auth_frm.is_valid():
        try:
            user = authenticate(
                username=auth_frm.cleaned_data['username'],
                password=auth_frm.cleaned_data['password'])
            login(request, user)
        except Exception:
            pass

            #return the same form and say login failed

        return HttpResponseRedirect('')

    return render(
        template_name, context, context_instance=RequestContext(request))
开发者ID:Johns7ta,项目名称:cottageinn,代码行数:29,代码来源:views.py

示例4: authenticate_user

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,代码行数:7,代码来源:general.py

示例5: login_view

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,代码行数:31,代码来源:views.py

示例6: login

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,代码行数:28,代码来源:user.py

示例7: loginUsuario

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,代码行数:25,代码来源:views.py

示例8: login_usuario

def login_usuario(request):
	menu=permisos(request)
	if request.method=="POST":
		form=AuthenticationForm(request.POST)
		if(form.is_valid()==False):
			username=request.POST["username"]
			password=request.POST["password"]
			resultado=authenticate(username=username,password=password)
			if resultado:
				login(request,resultado)
				request.session["name"]=username
				return HttpResponseRedirect("/blog/active/")
			else:
				request.session['cont']=request.session['cont']+1
				aux=request.session['cont']
				estado=True
				mensaje="Error en los datos "+str(aux)
				if aux>3:
					formulario2=fcapcha()
					datos={'form':form,'formulario2':formulario2,'estado':estado,'mensaje':mensaje}
				else:
					datos={'form':form,'estado':estado,'mensaje':mensaje}
				return render_to_response("usuario/login.html",datos,context_instance=RequestContext(request))
	else:
		request.session['cont']=0
		form=AuthenticationForm()
	return render_to_response("usuario/login.html",{"menu":menu,"form":form},RequestContext(request))
开发者ID:Luis456,项目名称:proyectodeseminari,代码行数:27,代码来源:views.py

示例9: login

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,代码行数:26,代码来源:views_user.py

示例10: index

def index(request):
    if request.method == 'POST': # If the form has been submitted...
        # ContactForm was defined in the the previous section
        print request.POST
        form = AuthenticationForm(data=request.POST) # A form bound to the POST data
        form2 = UserCreateForm(data=request.POST) # A form bound to the POST data
        
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
        
        
        if form2.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
       form = AuthenticationForm() # An unbound form
       form2 = UserCreateForm() # An unbound form

    return render(request, 'promotion/index.html', {
        'form_auth': form,
        'form_rec': form2,
    })
开发者ID:CASIRIUTGR3,项目名称:casir-messenger,代码行数:25,代码来源:views.py

示例11: login

def login(request, template_name="login.html"):

    if request.method == "GET":
        authenticationForm = AuthenticationForm()
    elif request.method == "POST":
        authenticationForm = AuthenticationForm(data=request.POST)
        if authenticationForm.is_valid():
            user = authenticationForm.get_user()

            auth_login(request, user)

            if user.is_superuser:
                return redirect('management')

            ucc = UDC.objects.filter(user=user)
            if ucc:
                request.session["UDC_ID"] = ucc[0].id
            else:
                raise Exception("User has not register to any SDDC")
            return HttpResponseRedirect(reverse("cloud"))

    return render_to_response(template_name, RequestContext(request, {
        "authenticationForm": authenticationForm,
        "error": authenticationForm.errors.get('__all__', None),
        "BRAND": settings.BRAND,
    }))
开发者ID:bluven,项目名称:eonboard,代码行数:26,代码来源:views.py

示例12: home

def home(request):
	form = AuthenticationForm()
	if request.method == "POST":
		form = AuthenticationForm(data=request.POST)
		if form.is_valid():
			login(request, form.get_user())
	return render_to_response('home.html', {'form': form}, context_instance=RequestContext(request))
开发者ID:Mowinski,项目名称:alarm,代码行数:7,代码来源:views.py

示例13: login

def login(request):
    if request.method == 'GET':
        redirect_to = request.GET.get('next', '/')
        return render(request, 'accounts/login.html', {
            'form': AuthenticationForm(),
            'next': redirect_to
        })
    else:
        form = AuthenticationForm(request, request.POST)
        if form.is_valid():
            login(request, form.get_user())
            return HttpResponseRedirect(redirect_to)

        redirect_to = request.POST.get('next', '/')
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                auth.login(request, user)
                return HttpResponseRedirect(redirect_to)
        return render(request, 'accounts/login.html', {
            'form': form,
            'next': redirect_to
        })
开发者ID:stanri,项目名称:caesar-web,代码行数:25,代码来源:views.py

示例14: login

def login(request):
    redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, "")

    if request.method == "POST":
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            # Worden we wel naar een veilige pagina gestuurd?
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            user = form.get_user()
            auth_login(request, user)

            # Primaire organisatie instellen
            if hasattr(user, "profile") and user.profile.current_organization:
                request.session["organization_pk"] = user.profile.current_organization.pk

            if not user.first_name or not user.email:
                # User information is not complete, redirect to register page.
                return redirect(register)

            return redirect(redirect_to)
    else:
        form = AuthenticationForm(request)

    redirect_field_name = REDIRECT_FIELD_NAME

    return render(request, "general/login.html", locals())
开发者ID:J3173,项目名称:alexia,代码行数:28,代码来源:views.py

示例15: is_authenticated

 def is_authenticated(self, request):
     """
     if user is_authenticated: return True
     else try to authenticate with django and return true/false dependent of
     result
     """
 
     # is authenticated
     if request.user.is_authenticated():
         return True
  
     # not authenticated, call authentication form
     f = AuthenticationForm(data={
         'username': request.REQUEST.get('username',''),
         'password': request.REQUEST.get('password',''),
     })
  
     # if authenticated log the user in.
     if f.is_valid():
  
         auth_login(request, f.get_user())
         # this ** should ** return true
         return request.user.is_authenticated()
  
     else:
         # fail to auth, save form errors
         #self.errors = f.errors
         return False
开发者ID:rubinovitz,项目名称:veracal,代码行数:28,代码来源:authentication.py


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