Django连接表连接任何用户名或密码

时间:2015-12-07 17:58:51

标签: python django

我是Django的新手,我尝试构建一个连接表单。 表单已创建,视图也可以继续。 无论用户名和密码如何,表单都会重定向我,就像我已经连接一样。

urls.py

from django.conf.urls import patterns, url, include

urlpatterns = patterns ('pmd.views',
url(r'^connexion$', 'connexion', name="se_connecter"),
url(r'^home$', 'p_home', name="home"),)

forms.py

"""Formulaire de connexion"""
class ConnexionForm(forms.Form):
    username = forms.CharField(label="Nom d'utilisateur", max_length=30)
    password = forms.CharField(label="Mot de passe", widget=forms.PasswordInput)

views.py

"""Vue utilisée pour se connecter"""
def connexion(request):
    connexionForm = ConnexionForm()
    if request.method == "POST":
        connexionForm = ConnexionForm(request.POST)
        if connexionForm.is_valid():
            u = connexionForm.cleaned_data["username"]
            p = connexionForm.cleaned_data["password"]
            user = authenticate(username=u, password=p)
            if user is not None and user.is_valid:
                login(request, user)
                reverse_lazy(home)
    else:
        connexionForm = ConnexionForm()
    return render(request, 'pmd/connexion.html', locals())

def p_home(request):
    return render(request, 'pmd/home.html', locals())

connexion.html

{% extends "pmd/base.html" %}
{# Ce commentaire Django ne sera pas visible dans le code source. #}
{% block title %}Connexion{% endblock %}
{% block content %}
<h1>Se connecter</h1>
    <form action="." method="post">
        {% csrf_token %}
        {{ connexionForm.as_p }}
        <input type="submit" value="Se connecter"/>
    </form>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您正在尝试对用户进行身份验证,如果用户存在,则您希望重定向到主页,否则您希望返回显示相应错误的表单。您需要在代码中进行一些更正。

试试这个

  

forms.py

def clean(self):
    self.user_cache = None
    cd = self.cleaned_data
    username = cd.get('username')
    password = cd.get('password')
    if username and password:

        self.user_cache = authenticate(username=username, password=password)
        if self.user_cache is None:
            raise forms.ValidationError(u"Wrong Username and Password Combination.")
        elif self.user_cache is not None and self.user_cache.is_active is False:
            raise forms.ValidationError(u'Sorry, Your Account is not Activated yet.')
    return cd

def get_user(self):
    return self.user_cache
  

views.py

from django.shortcuts import render, redirect
from django.template import RequestContext

def connexion(request):
  connexionForm = ConnexionForm()
  if request.method == "POST":
     connexionForm = ConnexionForm(request.POST)
     if connexionForm.is_valid():
         login(request, connexionForm.get_user())
         redirect('home')
   context={'connexionForm': connexionForm}
return render(request, 'pmd/connexion.html', context, context_instance=RequestContext(request))