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 關注
- 141 瀏覽
添加回答
舉報