'"Local variable referenced before assignment" Django error

I have no idea what may cause this issue. The only change I've made was add the loginquiredmixins to my class-based views.

Once I started stylising the login page I seem to have broken something, but I have no idea what exactly, which is a weird idea to have, what issue could CSS or some HTML cause, right?

I tried to assign the variables before the if statement and set it to null but that seems not to work properly as it throws an error regardless. I am using the basic django authentication system.

The exact error I am getting is - `local variable 'course' referenced before assignment.

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/login

Django Version: 3.0.7
Python Version: 3.7.3
Installed Applications:
['mainpage.apps.MainpageConfig',
 'quiz.apps.QuizConfig',
 'courses.apps.CoursesConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\views\generic\base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch
    return super().dispatch(request, *args, **kwargs)
  File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "H:\Learning Development Platform\learningplatform\courses\views.py", line 26, in get
    lesson_qs = course.lesson.filter(slug=lesson_slug)

Exception Type: AttributeError at /accounts/login
Exception Value: 'NoneType' object has no attribute 'lesson'

Here's my models.py file:

from django.contrib.auth import decorators
from django.db import models
from django.db.models.fields import SlugField
from django.urls import reverse


class Course(models.Model):
  slug = models.SlugField()
  title = models.CharField(max_length=120)
  description = models.TextField()


  def __str__(self) -> str:
      return self.title


  def get_absolute_url(self):
    return reverse('courses:detail', kwargs={'slug': self.slug})

  @property
  def lessons(self):
    return self.lesson_set.all().order_by('position') # syntax for foreignkey object


class Lesson(models.Model):
  slug = models.SlugField()
  title = models.CharField(max_length=120)
  course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True)
  position = models.IntegerField()
  video_url = models.CharField(max_length=200)

  def __str__(self) -> str:
      return self.title


  def get_absolute_url(self):
    return reverse(
      'courses:lesson-detail', 
      kwargs={
        'course_slug': self.course.slug,
        'lesson_slug': self.slug
        }
    )

And my views.py:

from django.shortcuts import render
from django.views.generic import ListView, DetailView, View
from .models import Course, Lesson
from django.contrib.auth.mixins import LoginRequiredMixin


class CourseListView(ListView):
    model = Course


class CourseDetailView(DetailView):
    model = Course


class LessonDetailView(LoginRequiredMixin, View):

    def get(self, request, course_slug, lesson_slug, *args, **kwargs):

      course_qs = Course.objects.filter(slug=course_slug)
      if course_qs.exists():
        course = course_qs.first()

      lesson_qs = course.lesson.filter(slug=lesson_slug)
      if lesson_qs.exists():
        lesson = lesson_qs.first()

      context = {
        'object': lesson
      }

      return render(request, 'courses/lesson_detail.html', context)


Solution 1:[1]

How much i understand...

in your "LessonDetailView" Class => In "get" method

Change this

lesson_qs = course.lesson.filter(slug=lesson_slug)

to

lesson_qs = course.objects.filter(slug=lesson_slug)

Then This Error will be solved:

Exception Type: AttributeError at /accounts/login

Exception Value: 'NoneType' object has no attribute 'lesson'

Solution 2:[2]

Seems like I have fixed it.

For some reason, adding the whole url that is responsible for the login_url solved the issue. The login_redirect was not working properly as it was redirecting a view that was causing the issue.

Thank you for all your help!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ZeevhY Org.
Solution 2 Mat