0

Entirely new to python and django framework.

Trying to build a login/registration system.'

After registering, redirects to home but user is not authenticated (returns false always)

views.py

def register(request):
if request.method == 'POST':
    form = SignUpForm(request.POST)
    if form.is_valid():
        form.save()
        username = form.cleaned_data.get('username')
        fullname = form.cleaned_data.get('fullname')
        password = form.cleaned_data.get('password1')
        user = authenticate(username=username, fullname=fullname, password=password)
        messages.success(request, f'Welcome to blaza {fullname}')
        if user is not None:
            login(request, user)
        return redirect('home')
else:
    form = SignUpForm()

return render(request, 'accounts/signup.html', {'form': form})

home.html

{% extends 'base.html' %}
{% block title %} Home {% endblock %}
{% block content %}
{% if user.is_authenticated %}
Welcome, {{user.username}}!
<a href="">Logout</a>
{% else %}
<P>You are not logged in</P>
<p><a href="">Login here</a></p>
{% endif %}  
{% endblock %}

It returns false always. "You are not logged".

I have tried {% if request.user.is_authenticated %} still not working.

Ibramazin
  • 958
  • 10
  • 30

2 Answers2

0

‍‍i‍‍s‍_authenticated is a method not a property. I think you forgot the parenthesis. Try this:

{% if request.user.is_authenticated() %}
  • 1
    Ttemplate syntax error. Could not parse the remainder: '()' from 'request.user.is_authenticated()' – Ibramazin Nov 20 '19 at 11:03
  • My bad. I am using django 1.8 where is_authenticated is method. It was changed after 1.10+ versions of django. Refer to this link - https://stackoverflow.com/questions/3644902/how-to-check-if-a-user-is-logged-in-how-to-properly-use-user-is-authenticated – Arnav Singh Chauhan Nov 20 '19 at 11:18
0

Have you saved the user after signing up ?

myuser.save()

I have attached the code which worked for me.

def signup(request):
if request.method == 'POST':

    username = request.POST['username']
    name = request.POST['name']
    email = request.POST['email']
    pass1 = request.POST['pass1']
    pass2 = request.POST['pass2']
    myuser = User.objects.create_user(username, email)
    myuser.set_password(pass1)
    myuser.us_name = name
    myuser.save()
    messages.success(request, "Your account has been sucessfully created. ")
    return redirect('signin')
return render(request, "authentication/signup.html")
Aadith
  • 1
  • 3