Django登录表单:我哪里出错了?

时间:2017-06-06 20:00:01

标签: python django django-forms django-templates django-views

真的不确定我的登录表单有什么问题并查看...我会在这里显示它,希望有人可能大致知道我哪里出错:

基本上是"提交" - 控制流不会进入form.is_valid nest ...

views.py:

def login_view(request):
    title = "login"
    form = UserLoginForm(request.POST or None)

    context = { "form": form, "title": title }

    print(request.user.is_authenticated())

    if form.is_valid():
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password")
        user = authenticate(username = username, password = password)
        login(request, user)
        print(request.user.is_authenticated())

        if username == "":
            error = "Please enter a username..."
            context = { "form": form, "title": title, 'error': error }

        if password =="":
            error = "Please enter a password..."
            context = { "form": form, "title": title, 'error': error }

        #If a password and username exists lets see if we can authenticate it:
        if username and password:
            if user is not None:
                #Checking if the user exists and the user is not none, if so continue, else raise an active user error:
                if user.is_active:
                    #Check that the password is correct and matches up to the password in the User.user model:
                    if user.check_password(password):
                        if user:
                            #One further check to see if user is true, if so let's login them in:
                            #Let's print server side that True if the the user is autheticated, if not print False:
                            print(request.user.is_authenticated())
                        else:
                            error = "This user does not exist..."
                            context = { "form": form, "title": title, 'error': error }
                    else:
                        error = "Incorrect password..."
                        context = { "form": form, "title": title, 'error': error }
                else:
                    error = "This user does not appear to be active."
                    context = { "form": form, "title": title, 'error': error }

        #Display the redirect if the form was valid and if user authentication was successful:

    return render(request, "blog/user_auth/login_form.html", context)

forms.py:

class UserLoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

    def clean(self, *args, **kwargs):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")

        # Alternative method for validation our authenticated user:
        # user_queryset = User.objects.filter(username=username)
        # if user_queryset() == 1:
        #     user = user_queryset.first()
        if username and password:
            user = authenticate(username = username, password = password)
            if not user:
                raise forms.ValidationError("This user does not exist..")

            if not user.check_password(password):
                raise forms.ValidationError("Incorrect password...")

            if not user.is_active:
                raise forms.ValidationError("This user does not appear to be active.")

        return super(UserLoginForm, self).clean(*args, **kwargs)

login_view.html(相关部分):

<form class="contact-form contact-form-two" name="contact-form" method="POST" action='.' enctype='multipart/form-data'>
  <div class="form-group">
  {% csrf_token %}
     <input type="text" class="form-control" required="required" placeholder="User ID">
     <input type="password" class="form-control" required="required" placeholder="Password">
     {% if error %}
       <div>{{ error }}</div>
     {% endif %}
     <button type="submit" class="btn btn-primary" value='{{ title }}'>Sign In</button>
  </div>        
</form><!-- /.contact-form -->

我没有收到任何错误 - 只是print(request.user.is_authenticated())打印不是真或假。

1 个答案:

答案 0 :(得分:1)

我建议只使用django附带的登录视图。它有基于函数和类的版本

from django.contrib.auth.views import login

urlpatterns = [
    ...
    url('login/$', login),
]

或基于班级

from django.contrib.auth.views import LoginView

urlpatterns = [
    ...
    url('login/$', LoginView.as_view()),
]

默认表单将为您完成所有验证和身份验证。

编辑:

如果使用基于类的视图,仍然可以进行自定义。例如,假设您要使用自定义模板和不同的成功网址。

#urls.py
from my_app.views import MyLoginView

urlpatterns = [
    ...
    url('login/$', MyLoginView.as_view()),
]


# views.py
from django.contrib.auth.views import LoginView

class MyLoginView(LoginView):
    template_name = 'my/custom/template.html'

    def get_success_url(self):
        return reverse('some-landing-page')

自定义模板如下所示。它将负责显示错误并渲染字段。

<form method="post">
    {% csrf_token %}

    {% if form.username.errors %}{% for error in form.username.errors %}<p class="error">{{ error }}</p>{% endfor %}{% endif %}
    <inpyt type="text" class="form-control" name="{{ form.username.name }}" placeholder="User ID" required {% if form.username.value %}value="{{ form.username.value }}"{% endif %}/>

    {% if form.password.errors %}{% for error in errors %}<p class="error">{{ error }}</p>{% endfor %}{% endif %}
    <input type="password" class="form-control" name="{{ form.passwords.name }}" placeholder="Password" required/>

    <input class="btn btn-primary" type="submit" />
</form>