Python django.contrib.auth.forms 模块,AuthenticationForm() 实例源码

我们从Python开源项目中,提取了以下24个代码示例,用于说明如何使用django.contrib.auth.forms.AuthenticationForm()

项目:til    作者:amitsaha    | 项目源码 | 文件源码
def login_view(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect('/post/')
    if request.method == 'GET':
        form = AuthenticationForm()
        return render(request, 'tilweb/login.html', {'form': form})
    if request.method == 'POST':
        form = AuthenticationForm(request=request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                print(user)
                login(request, user)
                return HttpResponseRedirect('/post/')
            else:
                print('User not found')
        else:
            # If there were errors, we render the form with these
            # errors
            return render(request, 'tilweb/login.html', {'form': form})
项目:djacket    作者:Djacket    | 项目源码 | 文件源码
def user_login(request):
    """
        View for logging users in.
    """

    redirect_to = request.POST.get(REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME, ''))
    login_form = AuthenticationForm(request, data=request.POST)
    if login_form.is_valid():
        # Ensure the user-originating redirection url is safe.
        if not is_safe_url(url=REDIRECT_FIELD_NAME, host=request.get_host()):
            redirect_to = settings.LOGIN_REDIRECT_URL
        # Okay, security check complete. Log the user in.
        auth_login(request, login_form.get_user())
        return redirect(settings.LOGIN_REDIRECT_URL if redirect_to == '' else redirect_to)
    else:
        return render(request, 'index.html', {'login_form': login_form, 'display': 'block', 'active': 'login'})
项目:django-authlib    作者:matthiask    | 项目源码 | 文件源码
def login(request, template_name='registration/login.html',
          authentication_form=AuthenticationForm,
          post_login_response=post_login_response):

    if request.method == 'POST':
        form = authentication_form(request, data=request.POST)

        if form.is_valid():
            auth.login(request, form.get_user())
            return post_login_response(request, new_user=False)
    else:
        form = authentication_form(request)

    response = render(request, template_name, {
        'form': form,
    })
    if request.GET.get('next'):
        response.set_cookie(
            REDIRECT_COOKIE_NAME,
            request.GET['next'],
            max_age=600)
    return response
项目:ottertune    作者:cmu-db    | 项目源码 | 文件源码
def login_view(request):
    if request.user.is_authenticated():
        return redirect(reverse('home_projects'))
    if request.method == 'POST':
        post = request.POST
        form = AuthenticationForm(None, post)
        if form.is_valid():
            login(request, form.get_user())
            return redirect(reverse('home_projects'))
        else:
            log.info("Invalid request: {}".format(
                ', '.join(form.error_messages)))
    else:
        form = AuthenticationForm()
    token = {}
    token.update(csrf(request))
    token['form'] = form

    return render(request, 'login.html', token)
项目:DjangoBlog    作者:liangliangyy    | 项目源码 | 文件源码
def form_valid(self, form):
        form = AuthenticationForm(data=self.request.POST, request=self.request)

        if form.is_valid():
            from DjangoBlog.utils import cache
            if cache and cache is not None:
                cache.clear()
            print(self.redirect_field_name)
            redirect_to = self.request.GET.get(self.redirect_field_name)
            auth.login(self.request, form.get_user())
            return super(LoginView, self).form_valid(form)
            # return HttpResponseRedirect('/')
        else:
            return self.render_to_response({
                'form': form
            })
项目:c3nav    作者:c3nav    | 项目源码 | 文件源码
def login_view(request):
    if request.user.is_authenticated:
        return close_response(request)

    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            login(request, form.user_cache)
            redeem_token_after_login(request)
            return close_response(request)
    else:
        form = AuthenticationForm(request)

    return render(request, 'site/account_form.html', {
        'title': _('Log in'),
        'form': form,
        'bottom_link_url': reverse('site.register'),
        'bottom_link_text': _('Create new account')
    })
项目:c3nav    作者:c3nav    | 项目源码 | 文件源码
def login_view(request):
    redirect_path = request.GET['r'] if request.GET.get('r', '').startswith('/editor/') else reverse('editor.index')
    if request.user.is_authenticated:
        return redirect(redirect_path)

    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            login(request, form.user_cache)

            if request.changeset.pk is not None:
                request.changeset.author = form.user_cache
                request.changeset.save()
            return redirect(redirect_path)
    else:
        form = AuthenticationForm(request)

    return render(request, 'editor/account_form.html', {
        'title': _('Log in'),
        'form': form,
        'bottom_link_url': reverse('site.register'),
        'bottom_link_text': _('Create new account')
    })
项目:SOMS    作者:qitan    | 项目源码 | 文件源码
def login(request, redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm):
    redirect_to = request.POST.get(redirect_field_name,
                                   request.GET.get(redirect_field_name, ''))
    if request.method == "POST":
        if request.POST.has_key('login'):
            form = authentication_form(request, data=request.POST)
            if form.is_valid():
                if form.get_user() and form.get_user().is_active:
                    # Ensure the user-originating redirection url is safe.
                    if not is_safe_url(url=redirect_to, host=request.get_host()):
                        redirect_to = resolve_url(djsettings.LOGIN_REDIRECT_URL)
                    auth_login(request, form.get_user())
                    Message.objects.create(type=u'????', user=request.user, action=u'????',
                                           action_ip=UserIP(request), content='???? %s'%request.user)
                    return HttpResponseRedirect(redirect_to)
            else:
                Message.objects.create(type=u'????', user=request.POST.get('username'), action=u'????',
                                       action_ip=UserIP(request), content=u'?????? %s'%request.POST.get('username'))
    else:
        form = authentication_form(request)
    return render(request, 'registration/login.html', {'form':form, 'title':'????'})
项目:ISS    作者:RyanJenkins    | 项目源码 | 文件源码
def user_config(request):
    ctx = {}

    if isinstance(request.user, AnonymousUser):
        ctx['embed_images'] = True
        ctx['embed_video'] = True
        ctx['allow_avatars'] = True
        ctx['allow_js'] = True
        ctx['editor_buttons'] = False
        ctx['login_form'] = AuthenticationForm()
    else:
        ctx['embed_images'] = request.user.embed_images()
        ctx['embed_video'] = request.user.embed_video()
        ctx['allow_js'] = request.user.allow_js
        ctx['editor_buttons'] = request.user.enable_editor_buttons
        ctx['allow_avatars'] = request.user.allow_avatars

    ctx['bbcode_settings'] = {
        'allow_js': ctx['allow_js'],
        'embed_images': ctx['embed_images'],
        'embed_video': ctx['embed_video'],
    }

    return ctx
项目:django-example-channels    作者:realpython    | 项目源码 | 文件源码
def log_in(request):
    form = AuthenticationForm()
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            login(request, form.get_user())
            return redirect(reverse('example:user_list'))
        else:
            print(form.errors)
    return render(request, 'example/log_in.html', {'form': form})
项目:django-act-as-auth    作者:PaesslerAG    | 项目源码 | 文件源码
def test_login_page_is_set_up_as_expected(self):
        self.goto_login_page()
        response = self.login_get_response
        self.assertEqual(200, response.status_code)
        form = response.context['form']
        self.assertTrue(
            isinstance(form, AuthenticationForm), type(form).__mro__)
项目:django-act-as-auth    作者:PaesslerAG    | 项目源码 | 文件源码
def get_login_form(request, authentication_form=AuthenticationForm, **kwargs):
    base_form = authentication_form
    if django.VERSION[:2] < (1, 6):
        class CaptureRequestActAsAuthForm(base_form):
            def __init__(self, *a, **kw):
                if request.method == 'POST':
                    kw.setdefault('request', request)  # "backport" from 1.6
                super(CaptureRequestActAsAuthForm, self).__init__(*a, **kw)

        base_form = CaptureRequestActAsAuthForm

    if not issubclass(base_form, InitialValuesFromRequestGetFormMixin):
        class InitialFromQueryAuthForm(
                InitialValuesFromRequestGetFormMixin, base_form):

            @property
            def query2initial(self):
                return super(InitialFromQueryAuthForm, self).query2initial + \
                        ('username',)

        base_form = InitialFromQueryAuthForm
    else:
        # TODO: raise warning if it doesn't have username in query2initial
        pass

    return base_form
项目:onreview    作者:ichi404gh    | 项目源码 | 文件源码
def login_request(request):
    if(request.method == 'GET'):
        context={
            'next':request.GET.get('next','/'),
            'form':AuthenticationForm(request)
        }

        return render(request, 'login.html', context)
    else:
        form = AuthenticationForm(None, request.POST or None)
        if(form.is_valid()):
            login(request, form.get_user())
            return redirect(request.POST['next'] or '/', permanent=False)
        return redirect(reverse("login"), permanent=False)
项目:django_channels_example    作者:thisismsreddy    | 项目源码 | 文件源码
def log_in(request):
    form = AuthenticationForm()
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            login(request, form.get_user())
            return redirect(reverse('example:user_list'))
        else:
            print(form.errors)
    return render(request, 'example/log_in.html', {'form': form})
项目:django_instagram    作者:andyalam    | 项目源码 | 文件源码
def login_user(request):
    form = AuthenticationForm()

    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('index')

    return render(request, 'feeds/login.html', {
        'form': form
    })
项目:chores    作者:liberza    | 项目源码 | 文件源码
def overview(request, **kwargs):
    login_form = AuthenticationForm()
    weekly_chores = ScheduledChore.objects.filter(chore__frequency = 'weekly', done = False)
    sun_chores = ScheduledChore.objects.filter(chore__frequency = 'daily', done = False, day = 0)
    mon_chores = ScheduledChore.objects.filter(chore__frequency = 'daily', done = False, day = 1)
    tue_chores = ScheduledChore.objects.filter(chore__frequency = 'daily', done = False, day = 2)
    wed_chores = ScheduledChore.objects.filter(chore__frequency = 'daily', done = False, day = 3)
    thu_chores = ScheduledChore.objects.filter(chore__frequency = 'daily', done = False, day = 4)
    fri_chores = ScheduledChore.objects.filter(chore__frequency = 'daily', done = False, day = 5)
    sat_chores = ScheduledChore.objects.filter(chore__frequency = 'daily', done = False, day = 6)
    return render(request, 
                  'overview.html', 
                   {'weekly_chores':weekly_chores,
                    'sun_chores':sun_chores,
                    'mon_chores':mon_chores,
                    'tue_chores':tue_chores,
                    'wed_chores':wed_chores,
                    'thu_chores':thu_chores,
                    'fri_chores':fri_chores,
                    'sat_chores':sat_chores,
                    'sun_rows':len(sun_chores)+1,
                    'mon_rows':len(mon_chores)+1,
                    'tue_rows':len(tue_chores)+1,
                    'wed_rows':len(wed_chores)+1,
                    'thu_rows':len(thu_chores)+1,
                    'fri_rows':len(fri_chores)+1,
                    'sat_rows':len(sat_chores)+1,
                    'login_form':login_form,
                    'user':request.user})

# sign the user in.
项目:chores    作者:liberza    | 项目源码 | 文件源码
def signin(request, *args, **kwargs):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = authenticate(username=request.POST['username'], password=request.POST['password'])
            if user is not None:
                login(request, user)
                return HttpResponseRedirect('/')

    else:
        form = AuthenticationForm()
    variables = RequestContext(request, {'form':form})
    return render_to_response('login.html', variables)

# log the user out.
项目:serveradmin    作者:innogames    | 项目源码 | 文件源码
def failoverlogin(request):
    if not getattr(settings, 'IS_SECONDARY', False):
        return HttpResponseForbidden()

    try:
        urlopen(settings.PRIMARY_CHECK_URL, timeout=1)
    except (socket.timeout, socket.error, URLError):
        pass
    else:
        error_msg = "Primary server is up, therefore login isn't allowed here."
        return HttpResponseForbidden(error_msg)

    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            if user and user.is_active and user.is_superuser:
                login(request, user)
                return HttpResponseRedirect('/')
    else:
        form = AuthenticationForm()

    request.session.set_test_cookie()

    return TemplateResponse(request, 'failoverlogin.html', {
        'form': form,
    })
项目:tissuelab    作者:VirtualPlants    | 项目源码 | 文件源码
def login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None, extra_context=None):
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.REQUEST.get(redirect_field_name, '')

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

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

            return HttpResponseRedirect(redirect_to)
    else:
        form = authentication_form(request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request, template_name, context,
                            current_app=current_app)
项目:lost-n-found-service    作者:mafshar    | 项目源码 | 文件源码
def login_user(request):
    if request.user.is_authenticated():
        pk = signer.sign(str(request.user.pk))
        return HttpResponseRedirect('./users/' + pk + '/products')
    form = AuthenticationForm()
    return render(request, 'lostnfound/login.html', {'form': form})

#Render the signup view
项目:lost-n-found-service    作者:mafshar    | 项目源码 | 文件源码
def authenticate_user(request):
    if request.method == 'POST':
        if 'signup' in request.POST: #signup
            form = MyUserCreationForm(request.POST)
            if form.is_valid():
                new_user = form.save(commit=True)
                # new_user.save()
                user = authenticate(username=new_user.username, password=form.clean_password2())
                if user is not None:
                    login(request, user)
                    pk = signer.sign(str(new_user.pk))
                    return HttpResponseRedirect('./users/' + pk + '/products')
                else:
                    raise Exception
            else:
                return render(request, 'lostnfound/signup.html', {'form': form})
        else: #login
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                pk = signer.sign(str(user.pk))
                return HttpResponseRedirect('./users/' + pk + '/products')
            else:
                form = AuthenticationForm()
                return render(request, 'lostnfound/login.html', {'form': form, 'badLogin':True})
    else:
        return HttpResponseRedirect('./')

#Handles GET & POST by a finder
项目:ecommerce-django    作者:Ekluv    | 项目源码 | 文件源码
def get(self, request):
        if 'cart_id' not in request.session:
            return redirect('/')
        cart = models.Cart.objects.get(id=request.session['cart_id'])
        context = {
        'login_form': AuthenticationForm(),
        'object': cart,
        'guest_form': self.get_form(),
        }
        user_checkout = request.session.get('user_checkout_id')
        if not user_checkout:
            if request.user.is_authenticated():
                user_checkout, created  = UserCheckout.objects.get_or_create(user=request.user)
                request.session['user_checkout_id'] = user_checkout.id
        if user_checkout:
            billing_address = request.session.get('billing_address_id')
            shipping_address = request.session.get('shipping_address_id')
            if not (billing_address and shipping_address):
                return redirect('address')
            if not 'order_id' in request.session:
                order = Order.objects.create(user_id=user_checkout, billing_address_id=billing_address, shipping_address_id=shipping_address, cart_id=cart.id)
                request.session['order_id'] = order.id
            else:
                order = Order.objects.get(id=request.session['order_id'])
            context['order'] = order
        return render(request, self.template_name, context)
项目:ecommerce-django    作者:Ekluv    | 项目源码 | 文件源码
def post(self, request):
        form = self.get_form()
        if form.is_valid():
            email = form.cleaned_data.get('email')
            user_checkout, created  = UserCheckout.objects.get_or_create(email=email)
            request.session['user_checkout_id'] = user_checkout.id
            return self.form_valid(form)
        else:
            context = {
                'login_form': AuthenticationForm(),
                'guest_form': form
                }
            return render(request, self.template_name, context)
项目:bryn    作者:MRC-CLIMB    | 项目源码 | 文件源码
def login(request):
    """
    Copied from django source, but modified to reject where email not verified
    Displays the login form and handles the login action.
    """
    redirect_to = request.POST.get(REDIRECT_FIELD_NAME,
                                   request.GET.get(REDIRECT_FIELD_NAME, ''))

    if request.method == "POST":
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            print("Redirect to " + redirect_to)

            # Okay, security check complete. Log the user in.
            user = authenticate(username=form.cleaned_data['username'],
                                password=form.cleaned_data['password'])

            if user:
                teams = Team.objects.filter(teammember__user=user)
                if not user.userprofile.email_validated:
                    messages.error(
                        request,
                        "Please validate your email address "
                        "by following the link sent to your email first.")
                elif not user.is_active:
                    messages.error(
                        request,
                        "Sorry, your account is disabled.")
                elif not any(team.verified for team in teams):
                    messages.error(
                        request,
                        "Your team hasn't been verified yet. Please "
                        "check back later.")
                else:
                    # All conditions met, login
                    auth_login(request, user)
                    return HttpResponseRedirect(redirect_to)

            return HttpResponseRedirect(reverse('user:login'))
    else:
        form = AuthenticationForm(request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        REDIRECT_FIELD_NAME: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }

    return TemplateResponse(request, 'userdb/login.html', context)