+-

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唯一的出路?
最佳答案
你需要做的两件事:
首先将您的网址更改为:
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'
点击查看更多相关文章
转载注明原文:如何在django 2.0的detailview中使用 - 乐贴网