View returning user as None

52 Views Asked by At

So, I'm creating a user confirmation system where a code is created, stored in the session and send through email

I made some prints inside the view that is used to confirm the code and active the user, the code is this one:

def activeThroughCode(request,):
    form = VerificationForm()
    if request.method == 'POST':
        form = VerificationForm(request.POST)
        if form.is_valid:
            entered_code = request.POST.get('verification_code')

            stored_code = request.session.get('verification_code')
            
            print("Entered Code:", entered_code)
            print("Stored Code:", stored_code)

            username = User.objects.get('username')

            if entered_code == stored_code:
                print(username)
                try:
                    user = User.objects.get(username=username)
                    user.is_active = True
                    user.save()
                    messages.success(request, f'Your account is active with success.')
                    return redirect('login')
                except User.DoesNotExist:
                    messages.error(request, 'Incorrect verification code.')
                    return redirect('login')

               
            else:
                messages.error(request, f"It wasn't possible to confirm your email")

    return render(request, 'activate.html',{'form': form})

When digiting the code in my form, I can confirm through terminal the entered code and stored code are the same, and everything is ok until here

but, for validating my user, I need, obviously, request the user to active and save it, but the result for

 username = User.objects.get('username')

            if entered_code == stored_code:
                print(username)

is None.

I'm 99% sure it's the only error, because my Exception is being printed to me, so it means the code confirmation is actually working

my forms:

class   MyUserCreationForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username','email','password1','password2']

class VerificationForm(forms.Form):
    verification_code = forms.CharField(label='Verification Code', max_length=10)

any idea of what could be wrong?

2

There are 2 best solutions below

1
Sahil On

If you obtain some values from your database. At that time, write this line

model  = User

get username from to database

user  =  User.objects.get(username =username)

in your case

 user = User.objects.get(username)--->> that is wrong

and

form.is_valid():-->write like this
0
yedpodtrzitko On

you have a bug on line 5:

if form.is_valid:

This will always return True, because it just check the method exists. It should be a call of the method instead:

if form.is_valid():