Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 875
Raj Mehta Avatar asked Mar 14 '17 17:03

Raj Mehta


1 Answers

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.

like image 58
Daniel Roseman Avatar answered Oct 14 '22 19:10

Daniel Roseman