Python Django 自定义登录页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35773576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:56:26  来源:igfitidea点击:

Django custom login page

pythondjangovalidationlogin

提问by chazefate

I have a custom Django login page. I want to throw an exception when username or password fields are empty. How can I do that?

我有一个自定义的 Django 登录页面。当用户名或密码字段为空时,我想抛出异常。我怎样才能做到这一点?

My view.py log in method :

我的 view.py 登录方法:

def user_login(request):
    context = RequestContext(request)
    if request.method == 'POST':
        # Gather the username and password provided by the user.
        # This information is obtained from the login form.
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        print("auth",str(authenticate(username=username, password=password)))

        if user:
            # Is the account active? It could have been disabled.
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/')
        else:
            return HttpResponse("xxx.")
    else:
        # Bad login details were provided. So we can't log the user in.
        print ("Invalid login details: {0}, {1}".format(username, password))
        return HttpResponse("Invalid login details supplied.")
    else:
        return render_to_response('user/profile.html', {}, context)

I tried this and it didn't work: This is forms.py

我试过了,但没有用:这是 forms.py

def clean_username(self):
    username = self.cleaned_data.get('username')
    if not username:
        raise forms.ValidationError('username does not exist.')

采纳答案by p3y4m

You can use login view, which is provided by Django. So your login.html should look like that example.

您可以使用 Django 提供的登录视图。所以你的 login.html 应该看起来像那个例子。

<form class="login" method="POST" action="/login/">

  {% csrf_token %}

  {{form.as_p}}

  <li><input type="submit" class="logBut" value="Log in"/></li>
  </form>

And remember urls.py !

记住 urls.py !

url(r'^login/$','django.contrib.auth.views.login', {'template_name': '/login.html'}),

回答by Alasdair

The correct approach is to use forms, instead of fetching the variables directly from request.POST. Django will then validate the form data, and display errors when the form is rendered in the template. If a form field is required, then Django will automatically display an error when the field is empty, you don't even need to write a clean_<field_name>method for this.

正确的方法是使用表单,而不是直接从request.POST. 然后 Django 将验证表单数据,并在模板中呈现表单时显示错误。如果需要一个表单字段,那么当该字段为空时,Django 会自动显示错误,您甚至不需要为此编写clean_<field_name>方法。

Django already has a built in login view. The easiest approach is to use this rather than writing your own. If you still want to write your own view, you will still find it useful to look at how Django does it.

Django 已经有一个内置的登录视图。最简单的方法是使用它而不是自己编写。如果您仍然想编写自己的视图,您仍然会发现查看 Django 是如何实现的。