【问题标题】:username with `james i. adams` not accepted with django routers带有“詹姆斯一世”的用户名。 django路由器不接受adams`
【发布时间】:2022-01-18 10:31:17
【问题描述】:

我已经为user 模型注册了路由器,该模型的视图集的lookup_url 为username。 用户名james adams 被路由器接受,但james i. adams 出现以下错误

django.urls.exceptions.NoReverseMatch: Reverse for 'user-detail' with keyword arguments '{'username': 'james i. adam', 'version': 'v1'}' not found. 4 pattern(s) tried: ['(?P<version>(v4))/users/(?P<username>[^/.]+)/?\\.(?P<format>[a-z0-9]+)/?$', '(?P<version>(v4))/users/(?P<username>[^/.]+)/?$', '(?P<version>(v1))/users/(?P<username>[^/.]+)/?\\.(?P<format>[a-z0-9]+)/?$', '(?P<version>(v1))/users/(?P<username>[^/.]+)/?$'] 

有人可以指导我,我怎样才能在注册了路由器的情况下允许这样的用户名用于 url 模式?

提前致谢

【问题讨论】:

  • 我看到你确实有一个答案,但更标准的做法可能是为记录生成一个唯一的 slug 并在 URL 中使用它而不是实际的用户名。如果您查看此问题的 SO URL,那正是他们在那里所做的......

标签: django django-rest-framework django-rest-viewsets drf-nested-routers


【解决方案1】:

如您所见,URL values excludes . 的默认正则表达式:

/users/(?P<username>[^/.]+)/
                       ^

您将不得不更改该正则表达式;如果您使用的是视图集,则很简单:

class UserViewSet(ModelViewSet):
    lookup_value_regex = '[^/]+'

【讨论】:

  • 非常感谢!它有效:) 只是想知道您是否知道默认情况下它们不允许. 字符的任何具体原因?是不是因为它可能存在安全漏洞或导致一些无效的网址?
  • 可能是因为它接受了URL中的.json.xml等来切换不同的返回格式。
  • 好的,谢谢 :)
猜你喜欢
  • 2012-06-06
  • 1970-01-01
  • 2019-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多