Django实现关注/取消关注按钮遇TypeError错误求助
问题排查:关注/取消关注按钮出现TypeError错误
错误信息:TypeError at /follow/4 follow() got an unexpected keyword argument 'user_id'
相关代码
models.py
class User(AbstractUser): following = models.ManyToManyField( "self", blank=True, related_name="followers", symmetrical=False ) def __str__(self): return str(self.username)
urls.py
path("profile/<int:user_id>", views.profile, name="profile"), path("follow/<int:user_id>", views.follow, name="follow"),
profile.html
<div class="row"> <b> following : </b> <p class="text-muted"> {{ profile.following.count }} </p> <b> followers : </b> <p class="text-muted"> {{ profile.followers.count }} </p> </div> {% if user.is_authenticated %} {% if user in profile.following.all %} <a href="{% url 'follow' user.id %}" class="btn btn-primary">Unfollow</a> {% else %} <a href="{% url 'follow' user.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 %}
views.py
def profile(request, user_id): profile = User.objects.get(pk = user_id) context = { "profile": profile, } return render(request, "network/profile.html", context) def follow(request, user_id): authorObj = User.objects.get(pk=user_id) currentUserObj = User.objects.get(pk=request.user.pk) following = authorObj.following.all() if user_id != currentUserObj.pk: if currentUserObj in following: authorObj.following.remove(currentUserObj) else: authorObj.following.add(currentUserObj) return HttpResponseRedirect(reverse("index"))
错误原因排查与修复
1. 解决TypeError问题
这个错误的核心是Django调用follow视图时,传递的user_id参数不被函数接受,按以下步骤排查:
- 核对参数名一致性:确保
urls.py中的<int:user_id>和views.py中follow函数的user_id参数拼写完全一致(不要出现userid、user_idd这类拼写错误)。 - 检查参数顺序:视图函数必须以
request作为第一个参数,user_id作为第二个,即def follow(request, user_id):,顺序颠倒会直接触发该错误。 - 重启开发服务器:修改代码后未重启服务器会导致旧代码残留,重启后再测试。
- 检查函数重复定义:确保
views.py中只有一个follow函数,没有同名函数覆盖正确定义。
2. 修复模板逻辑错误(功能逻辑颠倒问题)
当前模板存在两处逻辑错误,虽然不是报错直接原因,但会导致关注功能失效:
- URL参数传递错误:模板中
{% url 'follow' user.id %}传递的是当前登录用户的ID,应该传递要关注的目标用户IDprofile.id:{% url 'follow' profile.id %} - 关注状态判断错误:当前判断
{% if user in profile.following.all %}是检查「目标用户是否关注了当前用户」,正确逻辑应该是检查「当前用户是否关注了目标用户」,可二选一:<!-- 方式1:通过当前用户的following列表判断 --> {% if profile in user.following.all %} <!-- 方式2:利用related_name="followers"判断 --> {% if user in profile.followers.all %}
3. 视图函数优化(可选)
可以简化视图代码,直接使用request.user获取当前用户,无需二次查询,同时重定向回目标用户的个人页面,提升体验:
def follow(request, user_id): author = User.objects.get(pk=user_id) current_user = request.user if author != current_user: if current_user in author.followers.all(): author.followers.remove(current_user) else: author.followers.add(current_user) return HttpResponseRedirect(reverse("profile", args=[user_id]))
内容的提问来源于stack exchange,提问作者Chuks
相关产品推荐
相关产品推荐

