【问题标题】:How to add username in url django如何在 url django 中添加用户名
【发布时间】:2020-12-24 15:19:04
【问题描述】:

Django 新手,这是一个简单的博客文章应用程序。如何在网址中包含帖子作者的姓名?

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

发布模型

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 

【问题讨论】:

标签: python django


【解决方案1】:

您可以添加一个额外的参数:

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

在视图中,可以对作者进行过滤,如果作者的用户名不正确,则不会显示任何内容:

class PostDetailView(DetailView):
    model = Post

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

我们可以使用包含作者用户名的.get_absolute_url() method [Django-doc]Post 对象生成一个URL:

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})

注意:通常使用settings.AUTH_USER_MODEL [Django-doc] 引用用户模型比直接使用User model [Django-doc] 更好。更多信息可以查看referencing the User model section of the documentation

【讨论】:

  • 您好,感谢您的回复。我收到此错误“未找到带有参数 '(1,)' 的 'post-detail' 的反向。尝试了 1 个模式:['post\\/(?P[^/]+) \\/(?P[0-9]+)\\/$']"
  • @sokoine:你可能有一个{% url 'post-detail' post.id %},但它需要作者的用户名,所以:{% url 'post-detail' author=post.author.username pk=post.id %}
猜你喜欢
  • 2016-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 2014-03-16
  • 2015-05-14
  • 1970-01-01
相关资源
最近更新 更多