Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django URL give me space between root and included urls

Tags:

So I create an url in root/project/urls.py with this lines

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'))
]

while in my 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()),
]

So it is expected to give me http://localhost:8000/users/register and http://localhost:8000/users/auth urls.

Meanwhile my request doesn't behave as expected.

enter image description here

apparently it returns me a space between the root path and include path. I check my root/project/settings.py file I don't find any weird settings. Does anybody know what is going on?

like image 961
Putra Avatar asked Feb 02 '18 06:02

Putra


2 Answers

The space is just for displaying how the URL is built up, on the debug screen only.

I have experienced the same and at first I too thought Django somehow added the space. In the end it really is that there is no match between the URL's specified and the URL in your browser. Safari doesn't display the full url, so error can happen quickly...

Some additional info on urls in Django can be found here.

like image 113
moojen Avatar answered Oct 11 '22 17:10

moojen


The error message in your screenshot states that the request URL is http://localhost:8000/users does not exist.

Here you redirects /users/ to app.urls:

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

But in app.urls, you never included a pattern for when the URL ends with only "/users/". Instead, "/users/register/" and "/users/auth/" are both specified.

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

So http://localhost:8000/users/register and http://localhost:8000/users/auth should be valid URLs, but http://localhost:8000/users is not.

You can add another URL pattern for when the URL ends at "/users/":

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

In conclusion, Django's actually not wrong about that page does not exist (404), it's because you hadn't match http://localhost:8000/users in any of the urlpatterns.

like image 28
Taku Avatar answered Oct 11 '22 15:10

Taku