I have two apps:
backend shop
I my urls in main app dir:
path('backend/', include('backend.urls')),
path('', include('shop.urls')),
the problem is if I write in my url: localhost:8000/backend/abc which not exist Django jumps over to shop.urls and the app is crashing because it can not find the slug and the query goes in fail.
How can I prevent if I go to the url /backend/somethingwhichnotexist is returning an 404 and not search in other app urls for this folder? I have thought that this is one of the main reason for split the urls in app folders.
Here are some urls from backend/urls.py:
from django.urls import path, re_path
from . import views as backend_views
from django.contrib.auth import views as auth_views
from froala_editor import views
from django.conf.urls import include
urlpatterns = [
path('stamdata/', backend_views.edit_masterdata),
path('praefikser/', backend_views.edit_prefixes),
path('leverandorer/', backend_views.suppliers_view),
path('leverandorer/add', backend_views.add_supplier),
]
handler404 = 'backend.views.page_not_found_view'
shop/urls.py
here the url stops:
path('<slug:category_slug>/<slug:slug_subcategory>/', butik_views.cat_or_article),
normally I don't want that a backend urls switches to frontend view
regards Christopher.
CodePudding user response:
You you said Django run through all of the URL patterns and stops till it finds its matching URL. SO, what has happen here is that when you type a URL with localhost:8000/backend/abc/ it runs through all the URLS before returning 404 to the client. So, it stops at the URL that support any string with 2 parameters in your case below URL.
path('<slug:category_slug>/<slug:slug_subcategory>/', butik_views.cat_or_article),
To get a 404 by adding a static word in you URL.
path('shop/<slug:category_slug>/<slug:slug_subcategory>/', butik_views.cat_or_article),
or
path('backend/', include('backend.urls')),
path('shop/', include('shop.urls')),
CodePudding user response:
For now I fixed it with
shop/views.py
if category_slug == 'backend':
response = render(
request,
'backend/404.html',
)
response.status_code = 404
return response
else:
until I found another solution. It looks like that the URL dispatcher is working like this:
Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info.
So for now I did not found another way.
Edit:
I added this in the end of backend/urls.py:
re_path(r'^.*/$', backend_views.page_not_found_view)
so after all working urls it goes to all other to the 404 view.