Django匿名用户点赞重定向至admin/login而非accounts/login问题求助
环境信息
- Django==3.0.8
- django-comments-xtd==2.6.2
相关代码(views.py)
@csrf_protect @login_required def like(request, comment_id, next=None): """ Like a comment. Confirmation on GET, action on POST. Templates: :template:`django_comments_xtd/like.html`, Context: comment the flagged `comments.comment` object """ comment = get_object_or_404(get_comment_model(), pk=comment_id, site__pk=get_current_site_id(request)) if not get_app_model_options(comment=comment)['allow_feedback']: ctype = ContentType.objects.get_for_model(comment.content_object) raise Http404("Comments posted to instances of '%s.%s' are not " "explicitly allowed to receive 'liked it' flags. " "Check the COMMENTS_XTD_APP_MODEL_OPTIONS " "setting." % (ctype.app_label, ctype.model)) # Flag on POST if request.method == 'POST': perform_like(request, comment) return next_redirect(request, fallback=next or 'comments-xtd-like-done', c=comment.pk) # Render a form on GET else: flag_qs = comment.flags.prefetch_related('user')\ .filter(flag=LIKEDIT_FLAG) users_likedit = [item.user for item in flag_qs] return render(request, 'django_comments_xtd/like.html', {'comment': comment, 'already_liked_it': request.user in users_likedit, 'next': next})
问题描述
匿名用户点击点赞按钮后,被重定向至http://localhost:8000/admin/login/?next=/%5Ecomments/like/3/,但期望重定向到http://localhost:8000/accounts/login/。当前settings.py中未配置LOGIN_URL,不清楚admin/login的来源,请问下一步该如何排查?
排查步骤
咱们一步一步来定位问题:
手动设置
LOGIN_URL做快速验证
Django默认的LOGIN_URL是'/accounts/login/',既然现在跳转到了admin登录页,先直接在settings.py里明确配置:LOGIN_URL = '/accounts/login/'重启服务器后测试,如果能正确跳转到目标页面,说明之前有隐性配置覆盖了默认值;如果还是跳admin,那问题大概率出在django-comments-xtd的内部逻辑或者项目的自定义设置上。
调试查看当前
LOGIN_URL的实际值
在like视图函数开头加一行调试代码,看看系统实际使用的LOGIN_URL是什么:from django.conf import settings @csrf_protect @login_required def like(request, comment_id, next=None): print(f"Current LOGIN_URL: {settings.LOGIN_URL}") # 添加调试代码 # 原函数代码...触发点赞操作后看控制台输出:如果是
'/admin/login/',说明这个值被某个地方修改了;如果是默认的'/accounts/login/',那就要检查login_required装饰器是否被自定义替换过。排查django-comments-xtd的配置与源码
这个第三方库可能有自己的登录跳转配置,先检查settings.py里有没有类似COMMENTS_XTD_LOGIN_URL的自定义设置。如果没有,去查看django-comments-xtd的源码,看看它是否重写了login_required或者在处理登录跳转时硬编码了admin的URL。检查URL配置与命名冲突
打开项目的urls.py,排查是否存在URL映射错误:- 有没有把
'/accounts/login/'指向了admin的登录视图? - 有没有自定义的login URL,其name被意外覆盖为
'admin:login'?
Django的login_required会根据LOGIN_URL的路径或name跳转,如果LOGIN_URL被设置为'admin:login',就会跳转到admin登录页。
- 有没有把
检查第三方应用与中间件
看看项目中有没有其他权限类第三方应用,这类应用可能会修改LOGIN_URL的默认值。另外,检查settings.py的中间件列表,有没有自定义中间件在请求处理过程中修改了登录跳转逻辑。
内容的提问来源于stack exchange,提问作者Trts

