Django如何通过带username参数的URL动态展示当前用户及其他用户资料页
问题根因
你当前的问题核心是ViewProfileView的get_object方法固定返回当前登录用户的资料,完全忽略了URL路径中传递的username参数,所以无论跳转链接传入的是谁的用户名,最终返回的都是当前用户的资料。另外你注释的get_context_data里有明显错误:用数值类型的id字段匹配字符串类型的用户名,必然会查询失败。
解决方案
第一步:修改ViewProfileView逻辑
直接重写get_object方法,根据URL传入的username参数查询对应的用户资料即可,不需要额外区分跳转来源:
from django.shortcuts import get_object_or_404 class ViewProfileView(generic.DetailView): model = Profile template_name = 'registration/view_profile.html' def get_object(self): # 从URL参数中获取username username = self.kwargs.get('username') # 根据username查询关联的Profile,不存在则返回404 profile = get_object_or_404(Profile, user__username=username) return profile
因为你导航栏的跳转链接已经传入了当前登录用户的user.username,项目页的跳转链接传入了project.owner.username,视图会自动根据传入的参数返回对应资料,天然满足你的两种使用场景。
可选:用DetailView原生属性简化实现
如果不想重写get_object,也可以通过配置DetailView的内置参数实现,因为你的Profile模型的slug字段已经和用户username保持一致:
class ViewProfileView(generic.DetailView): model = Profile template_name = 'registration/view_profile.html' # 指定URL中用于查询的参数名为username slug_url_kwarg = 'username' # 指定Profile模型中用于匹配的字段为slug slug_field = 'slug'
两种实现方式效果完全一致。
模板使用说明
视图查询到的资料对象会默认传入模板,变量名为object,你可以直接在view_profile.html中使用object.about、object.profile_pic等字段,也可以在get_context_data中给它起别名:
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['page_user'] = self.object return context
内容的提问来源于stack exchange,提问作者Zane Wilson
相关产品推荐
相关产品推荐

