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.