You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

django-waffle的waffle_status接口无法正确返回用户关联Flag状态

问题原因

waffle默认的waffle_status视图仅支持Session认证,而你通过Postman请求时使用的是DRF的JWT Token认证,原视图无法解析该Token,导致request.user始终为AnonymousUser,因此用户绑定的Flag状态无法正确返回。

你的测试用例能成功,是因为client.force_login()采用的是Session认证方式,符合waffle视图的默认认证逻辑。

解决方案

自定义支持JWT认证的waffle_status视图,替换原路由即可:

  1. 在你的应用(比如example)中创建views.py,添加以下代码:
from waffle.views import WaffleJSON
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated

class AuthenticatedWaffleJSON(WaffleJSON):
    # 同时支持JWT和Session认证,兼容前后端不同场景
    authentication_classes = [JWTAuthentication, SessionAuthentication]
    permission_classes = [IsAuthenticated]
  1. 修改项目根目录的urls.py,替换原waffle的waffle_status路由:
from django.urls import path, include
from waffle.urls import urlpatterns as waffle_urls
from example.views import AuthenticatedWaffleJSON

# 遍历waffle路由,替换waffle_status视图
for url_entry in waffle_urls:
    if url_entry.name == "waffle_status":
        url_entry.callback = AuthenticatedWaffleJSON.as_view()

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/v1/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('api/v1/', include([path('', include(example_urls))])),
    path('waffle/', include(waffle_urls)),
]
  1. Postman请求时,确保在Headers中正确携带JWT令牌:
Authorization: Bearer <你的access_token>

完成以上配置后,waffle_status视图就能正确识别登录用户,返回对应Flag的激活状态。

内容的提问来源于stack exchange,提问作者SoundWave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 11:53:15