【问题标题】:Django URL give me space between root and included urlsDjango URL 给我根和包含的 url 之间的空间
【发布时间】:2018-07-12 15:07:36
【问题描述】:

所以我用这行在 root/project/urls.py 中创建了一个 url

from django.conf.urls import include
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', include('app.urls'))
]

在我的 root/app/urls.py 中

from django.urls import path

from .views import UserView, AuthenticationView

urlpatterns = [
    path('register/', UserView.as_view()),
    path('auth/', AuthenticationView.as_view()),
]

所以预计会给我http://localhost:8000/users/registerhttp://localhost:8000/users/auth的url。

同时我的请求没有按预期运行。

显然它在根路径和包含路径之间返回了一个空格。我检查了我的 root/project/settings.py 文件,没有发现任何奇怪的设置。有人知道怎么回事吗?

【问题讨论】:

  • 当您的网址实际上是 app.urls 时,您是 include ing accounts.urls。你可以试试吗?
  • 你真的要去/users/auth/吗?看起来您只请求/users/
  • @JahongirRahmonov 我尝试使用 include 将 /auth/ 和 /register/ 包含在根 url 中。
  • 使用这个。 url(r'^your_url/$',views.your_view)

标签: python django url


【解决方案1】:

该空间仅用于在调试屏幕上显示 URL 的构建方式

我也有同样的经历,起初我也认为 Django 以某种方式增加了空间。最后,确实是指定的 URL 与浏览器中的 URL 不匹配。 Safari 不显示完整的 url,所以很快就会出错...

一些额外的info on urls in Django can be found here

【讨论】:

    【解决方案2】:

    您的屏幕截图中的错误消息指出请求 URL 为 http://localhost:8000/users 不存在。

    在这里您将/users/ 重定向到app.urls

    path('users/', include('app.urls'))
    

    但在app.urls 中,您从未包含过当 URL 仅以“/users/”结尾时的模式。而是指定了“/users/register/”和“/users/auth/”。

    urlpatterns = [
        path('register/', UserView.as_view()),
        path('auth/', AuthenticationView.as_view()),
    ]
    

    所以http://localhost:8000/users/registerhttp://localhost:8000/users/auth 应该是有效的网址,但http://localhost:8000/users 不是。

    当 URL 以“/users/”结尾时,您可以添加另一个 URL 模式:

    urlpatterns = [
        path('', AuthenticationView.as_view()), # maybe the same as /auth/ ?
        path('register/', UserView.as_view()),
        path('auth/', AuthenticationView.as_view()),
    ]
    

    总之,Django 对那个页面不存在(404)其实没有错,这是因为你没有在任何urlpatterns 中匹配http://localhost:8000/users

    【讨论】:

    • 它给我一个警告WARNINGS: ?: (2_0.W001) Your URL pattern '^$' has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path().
    • 哎呀,我的错,它应该是一个空字符串。
    • 即使没有为用户添加索引路径,它也只是自行解决。太奇怪了,哈哈。还是谢谢。
    【解决方案3】:

    你尝试过使用正则表达式吗?

    path(r'^admin/', admin.site.urls)
    

    否则,在 Django 2 版本中,urls 架构已更改,我使用 url 函数而不是路径函数,这可能是解决您的问题的方法

    【讨论】:

    • re_path使用正则表达式。
    猜你喜欢
    • 2012-11-27
    • 2018-07-20
    • 2019-02-01
    • 2015-02-04
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2013-11-09
    相关资源
    最近更新 更多