How to Solve Error Message ‘reverse’ is not defined in Django

Posted on

This is an error that appear upon executing a page. The page itself is a part of the Django-based web application. The following image of the page execution will appear :

How to Solve Error Message 'reverse' is not defined in Django
How to Solve Error Message ‘reverse’ is not defined in Django

Actually, there is a script where the part of the script itself is generating the above error. The script is a file which is a part of a Django-based web application. The solution is simple. Just add the following syntax in the script :

class MyModel(models.Model):
    attribute = models.CharField(max_length=100)

    def __str__(self):
        return self.attribute

    def get_absolute_url(self):
        return reverse('url-name', kwargs={'pk':self.pk})

The reserved keyword of ‘reverse’ int the above script apparently is triggering an error. The above script or snippet code is a part of script from the models.py. It is a definition of a model in the form of a class. There is an additional function or method with the name of ‘get_absolute_url. In the function or the method, there is a line of code using the reserved keyword ‘reverse’.

Fortunately, the solution for this problem is never going to be too hard. According to the error message above in the picture, the name ‘reverse’ is not defined. It means that the keyword itself is not recognized.  Furthermore, the keyword ‘reverse’ is actually exist as part of the django reserved keyword. So, the problem is how can it be recognized in the script. The answer is simple and it is done by importing that keyword. The following is the line of script or snippet code for importing the ‘reverse’ keyword :

from django.urls import reverse

Just put the above line of script or snippet code in the models.py file. So, the ‘reverse’ keyword will be available for python to interpret the script. As soon as the declaration of the ‘reverse’ keyword exist, it will solve the problem. After that, just directly reload the page so the error will disappear.

Leave a Reply