【问题标题】:How to use <username> in detailview for django 2.0如何在 django 2.0 的详细视图中使用 <用户名>
【发布时间】:2018-09-13 16:53:05
【问题描述】:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=40, blank=True)
bio = models.TextField(max_length=500, null=True, blank=True)

def get_absolute_url(self):
    return reverse('userprofile:to_profile', args=[str(self.user.username)])

所以我制作了这个模型以将其保存为whatever.com/userprofile:to_profile/thisisusername

在网址上,我有

    path('accounts/profile/<username>/', ProfileDetailView.as_view(), name="to_profile"),

对于视图,我有

class ProfileDetailView(DetailView):
model = Profile
template_name = "account/profile.html"

我确实知道默认的 DetailView 需要 pk 和 slug 但每当我尝试传递用户名时

pk_url_kwarg = "username"

我收到一个错误

invalid literal for int() with base 10

无论如何我们可以将用户名用于通用详细视图吗?还是pk是唯一的出路?

【问题讨论】:

    标签: python django


    【解决方案1】:

    你需要做两件事:

    首先将您的网址更改为:

    path('accounts/profile/<str:slug>/', ProfileDetailView.as_view(), name="to_profile"),
    

    第二次定义获取SlugField的方法

    class ProfileDetailView(DetailView):
        model = Profile
        template_name = "account/profile.html"
    
        def get_slug_field(self):
        """Get the name of a slug field to be used to look up by slug."""
            return 'user__username'
    

    【讨论】:

    • 你也可以设置slug_field = "user__username"而不是覆盖get_slug_field
    • 是真的 Alasdair,我刚在这里测试过,都可以正常工作。
    【解决方案2】:

    您不能使用pk_url_kwarg,因为username 不是您在视图中显示的Profile 模型的主键。

    改写get_object

    from django.shortcuts import get_object_or_404
    
    def get_object(self):
        return get_object_or_404(Profile, user__username=self.kwargs['username'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-30
      • 2017-01-22
      • 1970-01-01
      • 2017-04-10
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多