使用表单登录无效

时间:2017-08-24 19:41:25

标签: django login

所以我正在创建一个带有表单的登录页面,问题是它不起作用:D

这是我的表格

forms.py

from django.contrib.auth.models import User
from django import forms

class UserForm(forms.ModelForm):

    password = forms.CharField(widget=forms.PasswordInput)
        class Meta:

    model = User
    fields = ['username', 'password',]

my views.py

def user_login(request):

    if request.method == 'POST':
        login_form = UserForm(request.POST)
        if login_form.is_valid():
            username = login_form.cleaned_data.get('username')
            raw_password = login_form.cleaned_data.get('password')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('restricted')
    else:
       login_form = UserForm()
return render(request, 'userlogin.html', {'login_form': login_form})

和我的HTML

<h2>Login</h2>
  <form method="post">
    {% csrf_token %}
    {{ login_form.username }}
      <br>
      {{ login_form.password }}
      <br>
    <button type="submit">Login</button>
  </form>

受限制是一个html,用于检查登录的用户。它运行正常 我不确定为什么它不起作用因为它一直将我重定向到loginuser.html页面,而不是将我重定向到仅在用户登录时才出现的受限页面。

2 个答案:

答案 0 :(得分:2)

您需要添加更多详细信息,但这是登录用户的分步指南:

forms.py

from django.contrib.auth import authenticate, get_user_model


User = get_user_model()

class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField()

def clean(self, *args, **kwargs):
    username = self.cleaned_data.get("username")
    password = self.cleaned_data.get("password")
    user_obj = User.objects.filter(username=username).first()
    if not user_obj:
        raise forms.ValidationError("Invalid credentials")
    else:
        if not user_obj.check_password(password):
            raise forms.ValidationError("Invalid credentials")
    return super(LoginForm, self).clean(*args, **kwargs)

和您的views.py

from django.contrib.auth import login
from .forms import LoginForm # or where you have the LoginForm

User = get_user_model()

def user_login(request):
    form = LoginForm(request.POST or None)
        if not request.user.is_authenticated:
            if form.is_valid():
                username_ = form.cleaned_data.get('username')
                user_obj = User.objects.get(username__iexact=username_)
                login(request, user_obj)
                return #something
            else:
                # show an error or etc
                ...
        else:
            # user is authenticated before and he is in.
            ...

和您的template.html

<form action="" method="post">
{% csrf_token %}
    <input type="text" name="username">
    <hr>
    <input type="password" name="password">
    <hr>
    <button type="submit">Login</button>
</form>

注意: 您可以使用django来呈现表单,但是您需要在表单字段上进行一些更改,例如密码(添加PasswordInput小部件)

答案 1 :(得分:0)

将包含表单错误的块添加到模板

<h2>Login</h2>
  <form method="post">
<!-- form errors -->
{% if login_form.errors %}
    {% for field in login_form %}
        {% for error in field.errors %}
                <strong>{{ error|escape }}</strong>
        {% endfor %}
    {% endfor %}
    {% for error in login_form.non_field_errors %}
            <strong>{{ error|escape }}</strong>
    {% endfor %}
{% endif %}
<!-- form errors -->
    {% csrf_token %}
    {{ login_form.username }}
      <br>
      {{ login_form.password }}
      <br>
    <button type="submit">Login</button>
  </form>