Django使用基于类的视图登录用户

时间:2016-12-15 20:11:00

标签: django django-views django-authentication django-login

我正在尝试记录用户,但是,我的视图似乎不起作用。呈现页面并显示表单和所有内容。但是当我输入有效的用户名和密码时,它只刷新页面而不是转到success_url。我认为这是我实现视图方法的方式。我认为login(request, user_obj)不被访问,如果是,request.user.is_authenticated()也是如此。

我还使用

包含我的登录表单
{% if user.is_authenticated %}
    {% include 'navbar_in.html' %}
{% else %}
    {% include 'navbar_out.html' %}
{% endif %}

它仅使用navbar_out.html,因此我知道我的代码无法访问login(request, user_obj)

用户模型:

# Create your models here.
class Usermie(models.Model):
    # associate fields with django built in user objects
    # this provides the authentication that we would need from the django built in utilities
    usermie_object = models.OneToOneField(User)

    # form fields
    id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=30, unique=True, blank=False)
    email = models.EmailField(max_length=30, unique=True, blank=False, null=False)
    first_name = models.CharField(max_length=30, blank=False)
    last_name = models.CharField(max_length=30, blank=False)
    birthday = models.DateField(blank=False)
    password = models.CharField(max_length=50, null=False)
    sex = models.CharField(max_length=1, blank=False)
    location = models.CharField(max_length=100, null=True)
    city = models.CharField(max_length=40, null=True)
    province = models.CharField(max_length=40, null=True)
    country = models.CharField(max_length=40, null=True)
    activated = models.IntegerField()  # will be 1 if account is activated, 0 otherwise.
    date_created = models.DateTimeField(default=timezone.now)  # the time the account is created
    date_activated = models.DateTimeField(null=True)  # when the account is activated via email

    def __str__(self):
        return self.username


# create a user object to attach to our forms (SignUp)object
def create_usermie_user_callback(sender, instance, **kwargs):
    usermie, new = Usermie.objects.get_or_create(usermie_object=instance)

查看:

from .models import Usermie
from django.shortcuts import render
from django.views.generic import View
from .forms import SignUpForm, LoginForm
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.contrib.auth import authenticate, login, logout

class UserLoginRegistration(View):
    form_class = LoginForm

    # Use initial to declare the initial value of form fields at runtime.
    # For example, you might want to fill in a username field with
    # the username of the current session.
    initial = {'key': 'value'}
    template_name = 'usermie/usertest.html'  # template form will be rendered on
    success_url = '/usermie/home/'  # template for successfully submitted form

    def get(self, request, *args, **kwargs):

        form_login = self.form_class(initial=self.initial)

        return render(request, self.template_name, {'form_login': form_login})

    # method for posting form
    def post(self, request, *args, **kwargs):

        # Accessing form with post data
        form_login = self.form_class(request.POST)

        # Checking if user is logged in
        if request.user.is_authenticated():
            # Making sure user does not log in twice,
            # just send user to profile.html if already logged in
            return HttpResponseRedirect(self.success_url)

        # Checking if the form is valid
        if form_login.is_valid():
            email = form_login.cleaned_data['email']
            password = form_login.cleaned_data['password']

            # NB! On Django docs Two methods to authenticate user and log them in
            # 1 call authenticate
            # 2 call login

            # Return a user_obj object if the username and password are valid
            # otherwise it will return null, the null variable is called None in python
            user_obj = authenticate(email=email, password=password)
            if user_obj is not None:
                if user_obj.is_active:
                    login(request, user_obj)
                    return HttpResponseRedirect(self.success_url)

            # If authentication failed
            else:
                return HttpResponseRedirect(self.template_name)
        # If form is not being posted, render form to template
        else:
            form_login = self.form_class(initial=self.initial)
            context = {'form_login': form_login}
            return render(request, self.template_name, context)

这是我的标记

<form class="navbar-form navbar-form-out" action="" method="post">
    {% csrf_token %}
    {% load widget_tweaks %}
    <div class="form-group">
        <label class="sr-only" for="{{ form_login.email.auto_id }}">{{ form_login.email.label }}</label>
        {% render_field form_login.email class="form-control" placeholder=form_login.email.label %}
    </div>
    <div class="form-group">
        <label class="sr-only" for="{{ form_login.auto_id }}">{{ form_login.password.label }}</label>
        {% render_field form_login.password class="form-control" placeholder=form_login.password.label %}
        {% for hidden in form_login.hidden_fields %}
            {{ hidden }}
        {% endfor %}
    </div>
    <div class="checkbox">
        <label>
            <input type="checkbox"> Remember me
        </label>
    </div>
    <button type="submit" name="" value="form_login" class="btn btn-default">Sign in</button>
</form>

1 个答案:

答案 0 :(得分:0)

可能是您的用户未处于活动状态且您没有处理该情况。尝试类似:

CSS