Django登录表单未经过身份验证

时间:2017-06-13 20:36:04

标签: django django-views django-authentication

尝试使用基于类的视图创建登录视图(第一次),并填充所有内容,但它一直说我的用户名无效。请帮我弄清楚什么是错的。

login.html (已编辑以显示整个表单):

<div class="card border-grey border-lighten-3 px-1 py-1 m-0">
            <div class="card-header no-border">
                <div class="card-title text-xs-center">
                    <img src="{% static 'images/logo/stack-logo-dark.png' %}" alt="branding logo">
                    {% if form.non_field_errors %}
                        {% for error in form.non_field_errors %}
                            <h6 class="card-subtitle line-on-side text-muted text-xs-center font-small-3 pt-2 danger"><span>Sorry, that login was invalid. Please try again.</span></h6>
                        {% endfor %}
                    {% endif %}
            </div>
        </div>
        <div class="card-body collapse in">
            <div class="card-block">
                <form class="form-horizontal" method="post" action="{% url 'dispatch:login' %}" role="form">
                    {% csrf_token %}
                    <fieldset class="form-group position-relative has-icon-left">
                        <input type="text" class="form-control" id="username" placeholder="Your Username" required>
                        <div class="form-control-position">
                            <i class="ft-user"></i>
                        </div>
                    </fieldset>
                    <fieldset class="form-group position-relative has-icon-left">
                        <input type="password" class="form-control" id="password" placeholder="Enter Password" required>
                        <div class="form-control-position">
                            <i class="fa fa-key"></i>
                        </div>
                    </fieldset>
                    <fieldset class="form-group row">
                        <div class="col-md-6 col-xs-12 text-xs-center text-sm-left">
                            <fieldset>
                                <input type="checkbox" id="remember-me" class="chk-remember">
                                <label for="remember-me"> Remember Me</label>
                            </fieldset>
                        </div>
                        <div class="col-md-6 col-xs-12 float-sm-left text-xs-center text-sm-right"><a href="recover-password.html" class="card-link">Forgot Password?</a></div>
                    </fieldset>
                    <button type="submit" class="btn btn-outline-primary btn-block"><i class="ft-unlock"></i> Login</button>
                </form>

views.py:(从教程中拉出)

class LoginView(FormView):
    """
    Provides the ability to login as a user with a username and password
    """
    success_url = '/'
    form_class = LoginForm
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'pages/login.html'

    @method_decorator(sensitive_post_parameters('password'))
    @method_decorator(csrf_protect)
    @method_decorator(never_cache)
    def dispatch(self, request, *args, **kwargs):
        # Sets a test cookie to make sure the user has cookies enabled
        request.session.set_test_cookie()

        return super(LoginView, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        auth_login(self.request, form.get_user())

        # If the test cookie worked, go ahead and
        # delete it since its no longer needed
        if self.request.session.test_cookie_worked():
            self.request.session.delete_test_cookie()

        return super(LoginView, self).form_valid(form)

    def get_success_url(self):
        redirect_to = self.request.REQUEST.get(self.redirect_field_name)
        if not is_safe_url(url=redirect_to, host=self.request.get_host()):
            redirect_to = self.success_url
        return redirect_to


class LogoutView(RedirectView):
    """
    Provides users the ability to logout
    """
    url = '/accounts/login/'

def get(self, request, *args, **kwargs):
    auth_logout(request)
    return super(LogoutView, self).get(request, *args, **kwargs)

forms.py

class LoginForm(forms.Form):
    username = forms.CharField(max_length=255, required=True)
    password = forms.CharField(widget=forms.PasswordInput, required=True)

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        user = authenticate(username=username, password=password)
        if not user or not user.is_active:
            raise forms.ValidationError("Sorry, that login was invalid. Please try again.")
        return self.cleaned_data

    def login(self, request):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        user = authenticate(username=username, password=password)
        return user

urls.py

app_name = 'dispatch'

urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^accounts/login/$', views.LoginView.as_view(), name='login'),
    url(r'^logout/$', views.LogoutView.as_view(), {'next_page': '/accounts/login'}, name='logout'),
    url(r'^profile/(?P<pk>\d+)/$', views.ProfileDetailView.as_view(), name='profile_detail'),
]

1 个答案:

答案 0 :(得分:0)

我不确定该教程为何如此复杂,但您只需要扩展默认登录视图并添加get_success_url函数和template_name

from django.contrib.auth.views import LoginView as AuthLoginView

class LoginView(AuthLoginView):
    success_url = '/'
    template_name = 'pages/login.html'
    redirect_field_name = REDIRECT_FIELD_NAME

    def get_success_url(self):
        redirect_to = self.request.GET.get(self.redirect_field_name)
        if not is_safe_url(url=redirect_to, host=self.request.get_host()):
            redirect_to = self.success_url
        return redirect_to

编辑:您的表单缺少输入上的name属性。这就是django正在寻找价值观的地方。

<input type="text" name="{{ form.username.name }}" />
<input type="password" name="{{ form.password.name }}" />