This article will show an alternative of solving an error message exist upon executing a certain script which is part of the Django-based web application. In the application, there is an attempt to access a certain url of the Django-based web application. The definition exist actually not in the urls.py of the application. But it exist in the models.py file as follows :
class MyModel(models.Model): attribute = models.CharField(max_length=100) def __str__(self): return self.attribite def get_absolute_url(self): return reverse('url-name', kwargs={'pk':self.pk})
Apparently, the url definition above in the get_absolute_url(self) function is invalid. The following is the image of the error message :
The url is not accessible, although in order to reach out for the model, the definition has already exist in the models.py. The definition itself exist in the function of get_absolute_url(). But the main problem is, it is not accessible as in the above image. After checking the main urls.py file in the project of the Django-based web application, apparently there is no definition of the url itself. The definition of the url itself must be exist in the main urls.py file. Just define it as follows :
from django.urls import path urlpatterns = [ path('url-name', MyModel.as_view() name='url-name'), ... ]
So, the above definition is actually to load the model as a view. The url for accessing the model exist in the function of ‘get_absolute_url’. But off course the definition must also exist in the ‘urls.py’ file. By defining the url name in the urls.py file, the page with the url of ‘/url-name’ is accesible. In this context, the ‘/url-name’ is just an example. The urls.py itself can be the url definition in the main project or in the application itself. But the main concern is that the url in the models.py definition must also be exist also in the urls.py file as an url definition.