Django跨应用获取用户Profile数据失败问题求助
问题解决:Django模板无法显示Profile模型的身高、体重、年龄数据
你的代码存在一个拼写错误,导致模板无法获取到Profile实例的数据,这是核心问题:
在blog/views.py中,你错误地使用了request.users.profile,正确的写法应该是request.user.profile(注意是单数user,不是复数users)。
修正后的blog/views.py代码
# 记得先导入Profile模型 from users.models import Profile from django.contrib.auth.decorators import login_required @login_required def home(request): try: profile_instance = request.user.profile # 修正拼写错误 except Profile.DoesNotExist: profile_instance = None context = { 'posts': Post.objects.all(), 'title': 'Home', 'profile_instance': profile_instance, } return render(request, 'blog/home.html',context)
额外优化建议
自动创建Profile实例:
避免因用户无Profile实例导致的异常,可以用get_or_create自动生成空实例:@login_required def home(request): profile_instance, created = Profile.objects.get_or_create(user=request.user) context = { 'posts': Post.objects.all(), 'title': 'Home', 'profile_instance': profile_instance, } return render(request, 'blog/home.html',context)模板空值处理:
当身高/体重/年龄字段未填写时,模板显示友好提示:<p>Height: {{ profile_instance.height|default:"未设置" }}</p> <p>Weight: {{ profile_instance.weight|default:"未设置" }}</p> <p>Age: {{ profile_instance.age|default:"未设置" }}</p>
内容的提问来源于stack exchange,提问作者Nayan Shenoy
相关产品推荐
相关产品推荐

