Django实现关注切换时UserProfile查询报DoesNotExist错误求助
Django用户关注功能查询UserProfile抛不存在异常的排查方案
问题背景
开发基于Django 3.0.3的用户关注切换功能时,执行UserProfile匹配查询始终抛出模型不存在异常,但直接核查数据库确认对应UserProfile记录已存在,无法定位报错诱因。
附相关代码与报错
视图逻辑
class UserProfileFollowToggle(View): def post(self, request, *args, **kwargs): print(request.POST) user_to_toggle = request.POST.get('username') print(user_to_toggle) profile_ = UserProfile.objects.get(user__username__iexact=user_to_toggle) user = request.user if user in profile_.follower.all(): profile_.follower.remove(user) else: profile_.follower.add(user) return redirect("/posts/list/")
前端表单
<form class='form' method='POST' action={% url 'profiles:toggle' %}> {% csrf_token %} <input type='hidden' name='username' value="{% if username %}{{ username }} {% else %}{{ testuser }}{% endif %}"> <button class='btn {% if is_following %}btn-default {% else %}btn-primary{% endif %}'>{% if is_following %}Unfollow {% else %}Follow{% endif %}</button> </form>
报错堆栈
Request Method: POST Request URL: http://127.0.0.1:8000/profiles/user-profile/ Django Version: 3.0.3 Python Version: 3.8.3 Traceback (most recent call last): ...(省略框架层堆栈路径) File "profiles\views.py", line 31, in post profile_ = UserProfile.objects.get(user__username__iexact=user_to_toggle) File "django\db\models\query.py", line 415, in get raise self.model.DoesNotExist( Exception Type: DoesNotExist at /profiles/user-profile/ Exception Value: UserProfile matching query does not exist.
根因定位
- 问题出在模板里的隐藏域取值:
value="{% if username %}{{ username }} {% else %}{{ testuser }}{% endif %}"中,{{ username }}后面多敲了一个空格,提交表单时会把带尾部空格的字符串作为username参数传给后端,这个不可见的多余空格就是导致查询永远匹配失败的核心原因。 - 后端取值时没有对参数做首尾去空清洗,直接用带空格的字符串做
iexact精确匹配——数据库存的真实用户名是没有多余空格的,自然匹配不到记录。 - 你在视图里打印的
user_to_toggle控制台输出,因为空格在终端里显示不明显,很容易忽略这个异常值。
修复步骤
- 删掉模板里
{{ username }}后面多余的空格,修正隐藏域取值:<input type='hidden' name='username' value="{% if username %}{{ username }}{% else %}{{ testuser }}{% endif %}"> - 后端增加参数清洗逻辑,做兜底兼容:
# 原取值替换为带去空处理的逻辑 user_to_toggle = request.POST.get('username', '').strip() # 空值拦截,避免无效查询 if not user_to_toggle: return redirect("/posts/list/") - 可以把裸
get查询替换为Django提供的get_object_or_404工具,后续遇到匹配不到的场景会自动返回404页面,不会抛出未捕获的模型异常打断流程。
内容的提问来源于stack exchange,提问作者Ahmed Yasin
相关产品推荐
相关产品推荐

