显示无效登录详细信息的最佳方式 - django表单

时间:2016-05-12 21:26:08

标签: python django authentication django-forms

我想向用户显示一条错误消息,提示用户名或密码无效,请再试一次'对于django中的登录表单,如果身份验证失败,但我不确定这样做的最佳方法是什么。 我考虑过设置一个将传递给模板的上下文变量,然后我可以使用CSS来表示带有表单的消息。如下所示:

        if user is not None:
            if user.is_active:
                # Redirect to a success page.
            else:
                # Return a 'disabled account' error message
        else:
            form = LoginForm()
            incorrect_login = True
            context = ('incorrect_login': incorrect_login, 'form':form)
            return render(request, 'home/home.html', context)
            # Return an 'invalid login' error message.

和html:

<form action="." method="POST"> {%csrf_token%}
  {%if incorrect_login%}
  <table class='failed_login'>
    {{form.as_table}}
  </table>
   {%else%}
  <table class='successful_login'>
    {{form.as_table}}
  </table>
  {%endif%}
  <p><input type='submit' value='Submit'></p>
</form> 
<!--Dont worry about the exact implementation of the html, its the basic idea im concerned with-->

但是,我觉得这是一个常见问题,因此django可能会在表单中提供更好的解决方案。我已经查看了有关使用表单的文档,但我不确定如何处理,主要问题是表单字段中存储的错误似乎更多地是关于验证输入类型。任何帮助或正确方向的观点都将受到赞赏。

2 个答案:

答案 0 :(得分:1)

Django附带built in authentication views,包括一个登录。你应该考虑使用登录视图,或者至少查看代码以了解它是如何工作的。

一个关键是只为GET个请求创建一个空白表单。您认为问题在于,form = LoginForm()时始终使用user is None创建新表单。这意味着绑定表单(form = LoginForm(request.POST))中的错误不会显示给用户。

答案 1 :(得分:0)

我将与您分享这种方法,也许它会有所帮助:

Views.py

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.views.generic import View
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.contrib.auth import login, authenticate, logout
from ..form import UsersForm


class LoginView(View):

    template_name = ['yourappname/login.html', 'yourappname/home.html']

    def get(self, request, *args, **kwargs):
        form = UsersForm()
        if request.user.is_authenticated():
            return render(request, self.template_name[1], t)
        return render(request, self.template_name[0], t)

    def post(self, request, *args, **kwargs):
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username = username, password = password)
        if user is not None:
            login(request, user)
            if user.is_active:
                return render(request, self.template_name[ 1 ])
        else:
            messages.add_message(
                request, messages.ERROR, "Incorrect user or password"
                )
            return HttpResponseRedirect(reverse( 'yourappname:login' ))

正如我所知,您已经知道模板交互,通过发送用户和密码并使用django消息发送。 如果您希望从表单中管理错误,可以使用clean方法:

https://docs.djangoproject.com/en/1.9/ref/forms/validation/

相关问题