Django-authenticate()具有该用户名的用户已存在 [英] Django - authenticate() A user with that username already exists

查看:418
本文介绍了Django-authenticate()具有该用户名的用户已存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我很困惑.

我正在尝试建立一个登录页面,但是每当我尝试登录时,django都会给出用户名已经存在的错误.我没有在任何地方使用save().

I'm trying to build a login page, but whenever I try to login, django gives the error that the username already exists. I haven't used save() anywhere.

我正在使用authenticate(),为此我引用了Django文档: https://docs. djangoproject.com/en/1.10/topics/auth/default/#how-to-log-a-user-in

I'm using authenticate(), I referred the Django docs for that: https://docs.djangoproject.com/en/1.10/topics/auth/default/#how-to-log-a-user-in

这是我的代码,请告诉我我要去哪里了

Here is my code, please tell me where I'm going wrong:

forms.py

class LoginForm(forms.ModelForm):
    username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'}))
    password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))

class Meta:
    model = User
    fields = ['username', 'password']

views.py

class LoginFormView(View):
    form_class = LoginForm
    template_name = 'login.html'

    # display a blank form
    def get(self, request):
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    # authenticate user
    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():

            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            user = authenticate(username=username, password=password)

            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('slrtcebook:home')

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

login.html

login.html

<div class="form-container">
    <form method="post" enctype="multipart/form-data">

        {% csrf_token %}
        {% for field in form %}
            {{ field }}
            {{ field.errors }}
        {% endfor %}

        <input id="submit" type="submit" value="Log in" />
    </form>
</div>

<p>Don't have an account? <a href="/">Register here</a></p>

推荐答案

请勿为此使用ModelForm;它将假定您正在尝试创建用户,并验证您是否可以使用输入的数据进行创建.只需使用标准格式-从forms.Form继承并删除Meta类.

Don't use a ModelForm for this; it will assume you're trying to create a user, and validate that you can do so with the data you've entered. Just use a standard form - inherit from forms.Form and remove the Meta class.

这篇关于Django-authenticate()具有该用户名的用户已存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆