Request.user.is_authenticated does not work after changing urls

So my code looked like this at first:

views.py

    from django.shortcuts import render, redirect
    from django.http import HttpResponse
    from .models import Information
    from django.db.models import Q
    from django.contrib import messages
    from django.contrib.auth import authenticate, login, logout
    from .forms import MyForm
    
    # rooms = [
    #   {'id': 1, 'name': 'Lets learn python!'},
    #   {'id': 2, 'name': 'Design with me'},
    #   {'id': 3, 'name': 'Frontend developers'},
    
    # ]
    
    
    def home(request):
      q = request.GET.get('q') if request.GET.get('q') !=None else ''
      information_search = Information.objects.filter(
          Q(host__icontains=q) |
          Q(hostname__icontains=q) |
          Q(port__icontains=q) |
          Q(platform__icontains=q) |
          Q(username__icontains=q) |
          Q(password__icontains=q) |
          Q(groups__icontains=q) 
        )
      sort_info = []
    
      informations = Information.objects.all()
      for i in informations:
        if i.groups not in sort_info:
          device_group = i.groups
          sort_info.append(device_group)
      information_count=information_search.count()
      context = {'informations':informations, 'information_search':information_search, 'information_count':information_count, 'sort_info':sort_info}
    
      return render(request, 'polls/home.html', context)
    
    
    def view_data(request, pk):
      information = Information.objects.get(id=pk)
      context = {'information':information}
    
      return render(request, 'polls/view_data.html', context)
    
    
    def loginPage(request):
    
      if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
    
        try:
          user = User.objects.get(username=username)
        except:
          messages.error(request, 'User does not exist')
    
        user = authenticate(request, username=username, password=password)
    
        if user is not None:
          login(request, user)
          return redirect('home')
        else:
          messages.error(request, "Username or password does not exist")
    
    
      context = {}
      return render(request, 'polls/login_register.html', context)
    
    
    
    def logoutUser(request):
      logout(request)
      return redirect('home')
    
    
    
    def edit_data(request, pk):
      information = Information.objects.get(id=pk)
      form = MyForm(instance=information)
    
      if request.method == 'POST':
        form = MyForm(request.POST, instance=information)
        if form.is_valid():
          form.save()
          return redirect('home')
    
      context = {'form': form}
      return render(request, 'polls/room_form.html', context)
    
    def delete_data(request, pk):
      information = Information.objects.get(id=pk)
      if request.method == 'POST':
        information.delete()
        return redirect('home')
      return render(request, 'polls/delete.html', {'obj': information})
    
    
    
    def my_form(request):
      if request.method == "POST":
        form = MyForm(request.POST)
        if form.is_valid():
          form.save()
          return redirect('home')
      else:
          form = MyForm()
      return render(request, 'polls/room_form.html', {'form': form})

urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('login/', views.loginPage, name="login"),
    path('logout/', views.logoutUser, name="logout"),

    path('', views.home, name='home'),
    path('view_data/<str:pk>/', views.view_data, name = "view_data"),
    path('edit_data/<str:pk>/', views.edit_data, name = "edit_data"),
    path('host/', views.my_form, name='my_form'),
    path('delete/<str:pk>/', views.delete_data, name='delete_data')


]

login_register.html

{% extends 'main.html' %}

{% block content %}

<div>
    <form method="POST" action="">
        {% csrf_token %}

        <label>Username:</label>
        <input type="text" name="username" placeholder="Enter Username" />

        <label>Password:</label>
        <input type="password" name="password" placeholder="Enter Password">
        <input type="submit" value="login"> 
    </form> 

</div>

{% endblock content %}  

I wanted to change the authentication system so that the home view is only returned if the user is logged in. I was able to show home view after the user logs in by making small changes to urls.py and login_register.html as follows:

views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Information
from django.db.models import Q
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from .forms import MyForm

# rooms = [
#   {'id': 1, 'name': 'Lets learn python!'},
#   {'id': 2, 'name': 'Design with me'},
#   {'id': 3, 'name': 'Frontend developers'},

# ]


def home(request):
  q = request.GET.get('q') if request.GET.get('q') !=None else ''
  information_search = Information.objects.filter(
      Q(host__icontains=q) |
      Q(hostname__icontains=q) |
      Q(port__icontains=q) |
      Q(platform__icontains=q) |
      Q(username__icontains=q) |
      Q(password__icontains=q) |
      Q(groups__icontains=q) 
    )
  sort_info = []

  informations = Information.objects.all()
  for i in informations:
    if i.groups not in sort_info:
      device_group = i.groups
      sort_info.append(device_group)
  information_count=information_search.count()
  context = {'informations':informations, 'information_search':information_search, 'information_count':information_count, 'sort_info':sort_info}

  return render(request, 'polls/home.html', context)


def view_data(request, pk):
  information = Information.objects.get(id=pk)
  context = {'information':information}

  return render(request, 'polls/view_data.html', context)


def loginPage(request):

  if request.method == 'POST':
    username = request.POST.get('username')
    password = request.POST.get('password')

    try:
      user = User.objects.get(username=username)
    except:
      messages.error(request, 'User does not exist')

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

    if user is not None:
      login(request, user)
      return redirect('home')
    else:
      messages.error(request, "Username or password does not exist")


  context = {}
  return render(request, 'polls/login_register.html', context)



def logoutUser(request):
  logout(request)
  return redirect('home')



def edit_data(request, pk):
  information = Information.objects.get(id=pk)
  form = MyForm(instance=information)

  if request.method == 'POST':
    form = MyForm(request.POST, instance=information)
    if form.is_valid():
      form.save()
      return redirect('home')

  context = {'form': form}
  return render(request, 'polls/room_form.html', context)

def delete_data(request, pk):
  information = Information.objects.get(id=pk)
  if request.method == 'POST':
    information.delete()
    return redirect('home')
  return render(request, 'polls/delete.html', {'obj': information})



def my_form(request):
  if request.method == "POST":
    form = MyForm(request.POST)
    if form.is_valid():
      form.save()
      return redirect('home')
  else:
      form = MyForm()
  return render(request, 'polls/room_form.html', {'form': form})

login_register.html

{% extends 'main.html' %}

{% block content %}

<div>
    <form method="POST" action="home/">
        {% csrf_token %}

        <label>Username:</label>
        <input type="text" name="username" placeholder="Enter Username" />

        <label>Password:</label>
        <input type="password" name="password" placeholder="Enter Password">
        <input type="submit" value="login"> 
    </form> 

</div>

{% endblock content %}  

However the bar at navbar.html which shows logout option if the user is logged in stops working..

navbar.html

{% extends 'main.html' %}

{% block content %}

<div>
    <form method="POST" action="home/">
        {% csrf_token %}

        <label>Username:</label>
        <input type="text" name="username" placeholder="Enter Username" />

        <label>Password:</label>
        <input type="password" name="password" placeholder="Enter Password">
        <input type="submit" value="login"> 
    </form> 

</div>

{% endblock content %}  

navbar is included in main.html as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>StudyBud</title>
</head>
<body>
    {% include 'navbar.html' %}

    {% block content %}

    {% endblock %}

</body>
</html>

and main.html is extended by other templates. Here main.html and navbar.html are stored in the templates folder of the root directory while other templates are in the 'polls' app folder.

If it helps here are my other files.

models.py

from django.db import models
from django.contrib.auth.models import User


class Information(models.Model):
    host = models.CharField(max_length=200, null=True, blank=False)
    hostname = models.CharField(max_length=200, null=True, blank=False)
    port = models.IntegerField()
    platform = models.CharField(max_length=200, null=True, blank=False)
    username = models.CharField(max_length=200, null=True, blank=False)
    password = models.CharField(max_length=200, null=True, blank=False)
    groups = models.CharField(max_length=200, null=True, blank=False)

    def __str__(self):
        return self.host

Here is home.html which extends main.html and is supposed to show the logout bar.

{% extends 'main.html' %}

{% block content %}



<h2>Inventory Management</h2>

<style>
    
    .home-container{
        display: grid;
        grid-template-columns: 1fr 3fr;
    }

</style>



<div class="home-container">
    
    <div>
        <h3>Browse Groups</h3>
        <hr>
        {% for i in sort_info %}

            <div>
                
                <a href="{% url 'home' %}?q={{i}}">{{i}}</a>
                <br><br>

            </div>

        {% endfor %}
    </div>

        

    <div>
        <h5>{{information_count}} devices registered</h5>
        <hr>
        <a href="{% url 'my_form' %}"> Add Device </a>
        <hr>
        {% for information in information_search %}
            <span>@{{information.host}}</span>
            <h3><a href="{% url 'view_data' information.id %}"> view </a></h3>
            <a href="{% url 'edit_data' information.id %}">Edit</a>
            <a href="{% url 'delete_data' information.id %}">Delete</a>

            <hr>

        {% endfor %}


    </div>


        

</div>

{% endblock content %}


</div>

Any insight please? I am a beginner and I was trying to make changes and implement my own features in the code i followed through a tutorial.

It looks like you're trying to check whether the user is authenticated in a view function, which isn't a good way to handle authentication. Instead, you should use the Django authentication middleware to handle authentication, and use the @login_required decorator to restrict access to views that require authentication.

Here's an example of how you would use the @login_required decorator:

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    # Code for the view goes here

In this example, the my_view function will only be accessible to authenticated users. If a user is not authenticated, they will be redirected to the login page.

You should also check your LOGIN_URL and LOGIN_REDIRECT_URL settings in settings.py, to make sure they are correct. If you are using a custom user model make sure to set the AUTH_USER_MODEL variable to the correct model path in settings.py

Back to Top