Django个人主页关注按钮异常:关注他人时关联自身账号
问题分析与修复方案
核心问题总结
你遇到的两个异常都是因为关注逻辑完全搞反,加上模板和视图里的参数错误导致的:
- 模板里判断关注状态的逻辑颠倒,且跳转时传错了用户ID
- 视图里操作的是当前用户自己而非目标用户,还有类型判断错误、缺少返回跳转
分步修复
1. 修复Profile.html模板错误
模板里有三处关键错误:
- 判断是否关注的逻辑写反了:
profile.authors.all是当前页面用户的粉丝列表(因为models里authors的related_name="fans",所以A.authors是关注A的人,也就是A的粉丝),我们要判断的是当前登录用户是否关注了页面用户,应该检查页面用户是否在当前用户的关注列表里 - 跳转
follow路由时传错了ID:你传的是当前用户的user.id,应该传页面用户的profile.id - 粉丝数和关注数的统计搞反了:粉丝数应该用
profile.fans.count(关注当前页面用户的人数),关注数用profile.authors.count(当前页面用户关注的人数)
修改后的Profile.html代码:
{% if user.is_authenticated %} {% if profile in user.authors.all %} <a href="{% url 'follow' profile.id %}" class="btn btn-primary">Unfollow</a> {% else %} <a href="{% url 'follow' profile.id %}" class="btn btn-primary"> Follow </a> {% endif %} {% else %} <button class="btn btn-outline-primary">Message</button> <p class="text-muted"> please, login to follow </p> {% endif %} <ul class="about"> {% if profile.fans.count <= 1 %} <li><span>{{ profile.fans.count }}</span>Follower</li> {% else %} <li><span>{{ profile.fans.count }}</span>Followers</li> {% endif %} <li><span>{{ profile.authors.count }} </span>Following</li> {% if post_count <= 1 %} <li><span>{{post_count}} </span>Post</li> {% elif post_count >= 2 %} <li><span>{{post_count}} </span>Posts</li> {% endif %} </ul>
2. 修复follow视图逻辑
视图里的错误包括:
- 初始版本错误地添加/移除当前用户自己,而非目标用户
- 修改后的版本里,
user_id != currentUserObj是int和User对象比较,永远为True,应该比较ID - 缺少重定向返回,导致操作后页面不刷新
最终正确的follow视图:
def follow(request, user_id): # 获取目标用户对象 target_user = User.objects.get(pk=user_id) current_user = request.user # 禁止用户关注自己 if user_id != current_user.id: if target_user in current_user.authors.all(): # 已关注则取消 current_user.authors.remove(target_user) else: # 未关注则添加 current_user.authors.add(target_user) # 重定向回目标用户的profile页面 return HttpResponseRedirect(reverse('profile', args=[user_id]))
验证逻辑正确性
修复后流程:
- 登录用户Profile1访问Profile2的页面
- 点击Follow按钮,会向
follow/2发送请求,视图将Profile2添加到Profile1的authors列表(即Profile1关注了Profile2) - 此时Profile2的
fans列表会自动包含Profile1(反向关联生效),所以Profile2的粉丝数+1,Profile1的关注数+1 - 页面重定向回Profile2,按钮会显示Unfollow,统计数字也正常更新
内容的提问来源于stack exchange,提问作者Chuks
相关产品推荐
相关产品推荐

