0
votes

I'm trying to make my custom login form using Django's user template. What i'm trying to do is the authentication of a user using username and password. Register works, every user is registered correctly, but when i'm trying to login using the correct fields, my:

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

returns None as value.

Here is my def login_view in views.py (i'm using logger to know what is going on)

def login_view(request):
    import logging
    logging.basicConfig(filename='mylog.log', level=logging.DEBUG)
    logging.debug('start')
    title = 'LOGIN'
    form = UserLoginForm()
    if request.user.is_authenticated:
        return redirect('board.html')

    if request.method == 'POST':
        form = UserLoginForm(request=request, data=request.POST)
        username= request.POST.get('username')
        password= request.POST.get('password')

        print(form.errors)

        if form.is_valid():
            logging.debug('form is valid')
            logging.debug('called form.save(), result=%s', UserLoginForm)
            logging.debug('username, result=%s', username)
            logging.debug('password, result=%s', password)
            user = authenticate(request, username=username, password=password)

            logging.debug('user, result=%s', user)
            ####
            if user is not None:
                login(request, user)
                logging.debug('username, result=%s', username)
                logging.debug('password, result=%s', password)
                messages.info(request, "You are now logged in as {username}")
                return redirect('board.html')
            else:
                messages.error(request, "Invalid username or password.")
                logging.debug('first else')
                return redirect('/')
            ####
        else:
            print(form.errors)
            logging.debug('errore form: , result=%s', form.errors)
            messages.error(request, "Invalid username or password.")
            logging.debug('second else')
            username = request.POST.get('username')
            password = request.POST.get('password')
            messages.error(request, "Invalid username or password.")
            logging.debug('username, result=%s', username)
            logging.debug('password, result=%s', password)
            return redirect('/')


    return render(request=request,
                  template_name="login.html",
                  context={"form": form , "title":title})

And that's my forms.py

class UserLoginForm(forms.Form):
    username = forms.CharField(label="username", help_text=False, widget=forms.TextInput(attrs={'class': 'form-control'}))
    password = forms.CharField(label="password", widget=forms.PasswordInput(attrs={'class': 'form-control'}))

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(UserLoginForm, self).__init__(*args, **kwargs)

    class Meta:
        model = User
        fields = ('username', 'password',)


    def clean(self, *args, **kwargs):
        import logging
        logging.basicConfig(filename='mylog.log', level=logging.DEBUG)



        logging.debug('I'm in forms.py')

        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        user = authenticate(self,username=username, password=password)
        logging.debug('sono dentro forms, user=%s', user)

        if user is not None:
            if not user:
                raise forms.ValidationError('No user found')
            if not user.is_active:
                raise forms.ValidationError('User is unable to login')

            return super(UserLoginForm, self).clean(*args, **kwargs)

And that's the logger

DEBUG:root:inizio
DEBUG:root:i'm in forms
DEBUG:root:i'm in forms, user=None
DEBUG:root:form is valid
DEBUG:root:called form.save(), result=<class 'scrumboard.forms.UserLoginForm'>
DEBUG:root:username, result=a
DEBUG:root:password, result=123
DEBUG:root:user, result=None
DEBUG:root: first else

Data as username and password are correctly sended to logger, so the post works fine. What i think is wrong is the action to search username and/or password in my database, and i'm already sure that these fields are stored in correctly.
Any suggestion?

2
I think i use authenticate wrong - blackJarvis

2 Answers

0
votes

The form validates the data sent from the frontend. Without it, you are pulling "unclean" data from request.POST.get('username'). To get the cleaned (validated) username from the form, use username = form.cleaned_data.get('username') and password = form.cleaned_data.get('password') instead.

0
votes

SOLVED:

The problem were in the way i was storing the password:

I was storing the field password as a normal string, without any encryption.

So i changed my register way with these lines in my register_view:

        if form.is_valid():
            user=form.save(commit=False)
            username = form.cleaned_data.get('username')
            **user.set_password(form.cleaned_data.get('password'))**

With this last line, the field password is being stored correctly, so now i can authenticate my user without any problem.