简体   繁体   中英

How do I login with with the user credentials in Django?

I'm working on a simple login and logout app in Django.

I wrote two views one for login and another for register.

Register view is working as expected. But login view is causing issues.

I'm using form.is_valid() in login view. That is where the issue is arising. If I print the form in else block, it is saying A user with that username already exists . This is happening even before trying to authenticate the user. Some one help me with this.

from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.http.response import HttpResponse
from django.shortcuts import render
from notes.forms import UserForm

def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    elif request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                return HttpResponse("Logged in")
            else:
                return HttpResponse("Wrong creds")
        else:
            print(form)
            return HttpResponse("else of is_valid()")

def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    elif request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            email = form.cleaned_data['email']
            existing = User.objects.filter(username=username)
            if existing:
                return HttpResponse('Username is already taken')
            else:
                User.objects.create(username=username, password = password, email=email)
                return HttpResponse("User created with "+ username +" username")
        else:
            return HttpResponse("Hi")

forms.py

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


class NoteForm(forms.ModelForm):

    class Meta:
        model = Note
        fields = '__all__'

class UserForm(forms.ModelForm):

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

The form.is_valid() call will validate the form, this is done through several steps . Depending on the fields of the model, it thus also checks the uniqness of the data.

The User [Django-doc] model has a uniqness constraint on the username , hence the UserForm can only be valid, if the username is not yet taken, or when the form contains a instance that is already stored in the database.

I therefore think that it might be better to create a LoginForm , like Django does with an AuthenticationForm [Django-doc] [GitHub] . For example:

class UserForm(forms.):
    username = forms.CharField()
    password = forms.CharField()

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