简体   繁体   中英

Django - authenticate() A user with that username already exists

Okay I'm confused.

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.

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

<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>

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.

For those of you who want the code here is what I did to fix it:

inside of views.py:

class UserLoginView(View):
form_class = LoginForm
template_name = 'music/login_form.html'

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

#proces form data
def post(self, request):
    form = self.form_class(request.POST)

    if form.is_valid():

        # user = form.save(commit=False)

        #cleaned (normalized) data
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        # user.set_password(password) #this is the only way to change a password because of hashing

        #returns the User obejects if credintials are correct
        user = authenticate(username=username, password=password)

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


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

inside of froms.py:

class LoginForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))
fields = ['username', 'password']

don't forget to also import LoginForm at the top of views.py, where you import UserForm:

from .forms import UserForm, LoginForm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM