1

New to Django, this is a simple blog post app. How do i include the name of a post's author in the url?

 urlpatterns = [
        path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    ]

post model

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank="true")
    content = models.CharField(max_length=400)

views.py

class PostDetailView(DetailView):

    model = Post 
1

1 Answer 1

2

You can add an extra parameter:

urlpatterns = [
    path('post/<str:author>/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
]

in the view, you can filter on the author such that if the author's username is incorrect, it will not present any content:

class PostDetailView(DetailView):
    model = Post

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(
            author__username=self.kwargs['author']
        )

We can generate a URL for a Post object with the .get_absolute_url() method [Django-doc] which includes the username of the author:

from django.urls import reverse

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank="true")
    content = models.CharField(max_length=400)

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'id': self.pk, 'author': self.author.username})

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

Hello, thanks for the response. I'm getting this error "Reverse for 'post-detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['post\\/(?P<author>[^/]+)\\/(?P<pk>[0-9]+)\\/$']"
@sokoine: you likely have a {% url 'post-detail' post.id %}, but it thus needs the username of the author, so: {% url 'post-detail' author=post.author.username pk=post.id %}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.