1 回答
TA贡献1951条经验 获得超3个赞
您需要添加BaseDetailView、定义get_object方法并添加'user'到上下文:
class UserProfileView(SelectRelatedMixin, BaseDetailView, TemplateView):
model = Profile
template_name = 'accounts/profile.html'
select_related = ('user',)
def get_object(self):
return self.get_queryset().get(user__username=self.kwargs['username'])
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
content['user'] = self.object.user
return context
或者,您可以将您的观点基于User模型,而不是Pofile(我认为这种方式更简单):
class UserProfileView(SelectRelatedMixin, BaseDetailView, TemplateView):
model = User
template_name = 'accounts/profile.html'
select_related = ('profile',)
def get_object(self):
return self.get_queryset().get(username=self.kwargs['username'])
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
content['user'] = self.object
return context
或者您甚至可以不费心添加'user'到上下文中,只需通过以下方式访问模板中的用户object
- 1 回答
- 0 关注
- 88 浏览
添加回答
举报