1

我正在集成 Django_hosts。我的前端 URL 和管理 URL 已成功集成并正常工作,但由于此错误,我的 REST API URL 仍然无法访问:

'NoReverseMatch at /en/api/'

该错误被追溯到 Django/urls/base.py,但我不确定是什么触发了它:

Traceback (most recent call last):
  File "/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
  File "/lib/python3.6/site-packages/django/shortcuts.py", line 148, in resolve_url
    return reverse(to, args=args, kwargs=kwargs)
  File "/lib/python3.6/site-packages/django/urls/base.py", line 86, in reverse
    raise NoReverseMatch("%s is not a registered namespace" % key)
django.urls.exceptions.NoReverseMatch: 'admin' is not a registered namespace

这些是我的 hosts.py 和 api_urls.py 文件:

# hosts.py
host_patterns = patterns(
    '',
    host(r'www', settings.ROOT_URLCONF, name='www'),
    host(r'admin', 'Project.admin_urls', name='admin'),
    host(r'api', 'Project.api_urls', name='api'),
)

# api_urls.py
urlpatterns += i18n_patterns (
           path('session_security/', include('session_security.urls')),
           path('', include('Project.apps.api.urls'), name='api'),
           ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

此外,在尝试转换此 url 时,用一块石头杀死两只鸟:

{% url 'profile' request.user.id %}

到这个网址:

{% host_url 'profile' host 'www' request.user.id %}

它没有抛出没有参数的 NoReverseMatch 错误,就好像忽略了参数一样。

任何了解此软件包或这些问题的人的任何帮助将不胜感激。

谢谢。

更新

我通过在 api_urls.py 文件中包含 admin.site url 解决了这个错误:

# api_urls.py
urlpatterns += i18n_patterns (
           path('session_security/', include('session_security.urls')),
           path('', include('Project.apps.api.urls'), name='api'),
           ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
           path('', admin.site.urls, name='admin'), <--This is key, but not sure exactly why.

但是,现在我遇到了一些奇怪的事情,这并不完全是一个错误,但对于我的用例来说实际上是一个错误。API 似乎不再识别 request.user,因此即使用户登录,API 也认为他是 AnonymousUser。

*API 和 Admin 子域均无法识别登录用户。似乎与SESSION cookie有关...

4

0 回答 0