Search code examples
pythondjangourlpostframe

Error: Reverse for 'article-detail' not found. 'article-detail' is not a valid view function or pattern name


I'm trying to use reverse in one of my model functions, but when I put the name of the url in the reverse, it shows the error of the title, and I'm not sure why this is happening, here's the code of the urls and the models.

models.py

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

# Create your models here.

class Post(models.Model):
    title = models.CharField(max_length= 255)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()

    def __str__(self):
        return self.title + ' | ' + str(self.author)
    
    def get_absolute_url(self):
        return reverse('article-detail', args =(str(self.id)))

app/urls.py

from django.urls import path
from app1 import views
from .views import PostView, ArticleDetailView, AddPostView

app_name = 'app1'

urlpatterns = [
    path('register/', views.register, name = 'register'),
    path('user_login/', views.user_login, name = 'user_login'),
    path('post/', PostView.as_view(), name = 'Post'),
    path('article/<int:pk>', ArticleDetailView.as_view(), name = 'article-detail'),
    path('add_post/',AddPostView.as_view(), name='addpost')
]

urls.py

from django.contrib import admin
from django.urls import path, include
from app1 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name = "index"),
    path('app1/', include('app1.urls')),
    path('logout/', views.user_logout, name='logout')
    
]

I would appreciate a lot if someone could tell me why this error is showing, I'm sure that it is in the last line of models.py, but I don't understand why it's popping, since the name matches with the url I want to call.


Solution

  • You forgot to mention the app_name. Try this

    class Post(models.Model):
        title = models.CharField(max_length= 255)
        author = models.ForeignKey(User, on_delete=models.CASCADE)
        body = models.TextField()
    
        def __str__(self):
            return self.title + ' | ' + str(self.author)
        
        def get_absolute_url(self):
            # return reverse('article-detail', args =(str(self.id)))
            return reverse('app1:article-detail', args = [str(self.id))]