Match all urls without the prefix in Django - python

I'm currently using the following urls.py:
api_patterns = [
url(r'^users/', include('users.urls', namespace='user')),
]
internal_patterns = [
# ...
]
urlpatterns = [
url(r'^api/', include(api_patterns)),
url(r'^internal/', include(internal_patterns)),
url(r'^admin/', include(admin.site.urls)),
url(r'^(?!(?:api|internal|admin)/)', MainView.as_view()),
]
The point of this config is to render MainView if url doesn't have the api, internal or admin prefix:
/api/users/... — found
/api/foo/ — not found
/foo/ — found
How can I make it simplier and more intent revealing?

I think your intent will be more clear if you do this in two urls:
url(r'^(api|internal|admin)/', SomeView.as_view()),
url(r'^.*', MainView.as_view())
MainView will be executed only if a url does not begin with api, internal or admin.
SomeView will be executed if a url begins with api/internal/admin but doesn't match the patterns above it. You can customize this view to either return a default 404 page, or perform other functions as you need.
Using your examples:
/api/users will execute include(api_patterns)
/api/foo will execute SomeView
/foo will execute MainView
Edit
To address the first point in your comment: url patterns are regexes, while you can extract these into variables to remove duplication, it can make code hard to read. Here's one example for removing duplication (I'm sure you can come up with others):
d = OrderedDict([
(r'api', api_patterns),
(r'internal', internal_patterns),
(r'admin', admin.site.urls),
])
main_view_re = r'^!({})/'.format('|'.join(d.keys()))
urlpatterns = [url(r'^{}/'.format(k), include(v)) for k, v in d]
urlpatterns.append(url(main_view_re, MainView.as_view()))

For django >= 3 rather use re_path:
from django.urls import re_path
urlpatterns = [
re_path(r'^.*',MainView.as_view())
]

urlpatterns = [
url(r'^api/', include(api_patterns)),
url(r'^internal/', include(internal_patterns)),
url(r'^admin/', include(admin.site.urls)),
url(r'', MainView.as_view()),
]
Leaving no prefix would allow you to catch any URL that a user might try after the URL conf matches the api, internal and admin url's.

Related

Reverse for 'hobbieswithCSS.html' not found. 'hobbieswithCSS.html' is not a valid view function or pattern name

I am trying to attach hobbieswithCSS.html file to my website, while using Django. I am a beginner when it comes to Django, so I have naturally came across some problems (in the title) like this.
I have this anchor tag on my homepage -
My Hobbies
I have this view in my views.py file -
def hobbieswithCSS(request):
return render(request,'basic_app/hobbieswithCSS.html')
I think, that the main problem will be with the urlpatterns in urls.py file, because I am not sure how to set it up. These are my urlpatterns -
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^basic_app/',include('basic_app.urls')),
url(r'^logout/$',views.user_logout,name='logout'),
url(r'^$', views.hobbieswithCSS, name='hobbieswithCSS'),
]
Could anybody please tell me, how could I change the code in order to make that hobbieswithCSS.html file display, when I am trying to run it on my server?
It must be:
My Hobbies
Without basic_app.
Also you have the same path for index and hobbies . You have to change your url path:
urlpatterns = [
url(r'^$', views.index, name='index'),
...
url(r'^hobbies/$', views.hobbieswithCSS, name='hobbieswithCSS'),
]
in your template update to
My Hobbies

Django : Cannot resolve the URLs pattern : Always Index page content is displayed

I am learning Django. I build an app in which I am setting up the URL patterns but in all cases it's displaying the data for the index page.
appTwo urls.py File :
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$', views.users, name='users'),
url(r'^$', views.help, name='help'),
]
MyProject urls.py file :
urlpatterns = [
url(r'^$', views.index, name='index'),
url('admin/', admin.site.urls),
url(r'^users/', include('appTwo.urls')),
url(r'^help/', include('appTwo.urls')),
]
If I call /users or /help, the browser display the data for index file only.
Is there something with a regex that I am doing wrong?
You're setting your urlpatterns in a wrong way. First of all, in you project's urls.py file you are saying that if a request is sent to /users or /help, then Django should look into your appTwo.urls. When Django gets there, it finds that the urlpatters are set so that everything that's empty after any of the aforementioned urls must be handled by the views.index, views.users and views.help. But as views.index is the first one in the list, then all the request end up being handled by that view.
By the way, if you're using Django >= 2.0 you no longer need to use the url() function, but the path() one instead, for which you can declare the paths as simple strings rather than regular expressions.
You should have something as follows:
MyProject/urls.py
from django.urls import path
urlpatterns = [
path('', include('appTwo.urls')),
path('admin/', admin.site.urls)
]
MyApp/urls.py
from django.urls import path
urlpatterns = [
path('', views.index, name='index'),
path('users/', views.users, name='users'),
path('help/', views.help, name='help'),
]
when django reaches here (in your apps url) while resolving the urls, see all three urls have empty regex as first param (so the first one will be selected), And as you see its index then you always show index page. You need to differentiate the urls. Something like this.
urlpatterns = [
url(r'^users/$', views.users, name='users'),
url(r'^help/$', views.help, name='help'),
url(r'^$', views.index, name='index'),
]
I think you also cant write url index with empty regex at top of other urls, otherwise it will always be selected.

Django Include() in urls.py with two apps

I believe this is a simple question but I am having a hard time figuring out why this is not working.
I have a django project and I've added a second app (sales). Prior to the second app, my urls.py simply routed everything to the first app (chart) with the following:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('chart.urls')),
]
and it worked fine.
I have read the docs over and over a looked at many tutorials, so my impression is that I can simply amend the urls.py to include:
urlpatterns = [
path('admin/', admin.site.urls),
path('sales/', include('sales.urls')),
path('', include('chart.urls')),
]
and it should first look for a url with sales/ and if it finds that then it should route it to sales.urls, and if it doesn't find that then move on and route it to chart.urls. However, when I load this and type in 127.0.0.1:8000/sales, it returns the following error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/sales/
Raised by: chart.views.index
which tells me that it is not routing my sales/ url to sales.urls but to chart.urls. When I change path('', include('chart.urls')), to path('', include('sales.urls')), it does route it to sales.urls so I know that my sales.urls file is set up correctly.
I know this is probably an easy question but I cannot figure it out with anything I've read. Any help is appreciated.
chart.urls:
from django.urls import path, re_path
from . import views
urlpatterns = [
path('dashboard/', views.chart, name='dashboard'),
path('', views.index, name='index', kwargs={'pagename': ''}),
path('<str:pagename>/', views.index, name='index'),
]
sales.urls:
from django.urls import path
from . import views
urlpatterns = [
path('sales/', views.sales, name='Sales Dashboard'),
]
I think the correct url for the sales page in your case would be http://127.0.0.1:8000/sales/sales/.
This is because sales/ is then looking in the included sales.urls and not finding any urls at the root / (the only url included there is at sales/ (within sales/) so will be sales/sales/
Reply to an OLD question but may be useful for others...
from django.urls import path, include
dont for get to import include
Do this:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('chart.urls')),
url(r'^sales/', include('sales.urls')),
]
you are not doing it properly since you are not telling your app where go once it is loaded .this r'^' to go directly to chart.url url(r'^', include('chart.urls')),

django, how to mapping no other address, but just domain?

myproject/urls.py
urlpatterns = [
url(r'^$', include('website-app.urls', namespace='website')),
]
website-app/urls.py
urlpatterns = [
url(r'^$', views.somedef, name='somename')
]
I want to connect url domain.com/ to views.somedef which is not in myproject.
What domain.com/ means is just domain and end of address with /.
It is with No other parameters.
domain.com/other/parameters/ has other parameters (other/parameters/), so it is not what I want.
If I run django with that above code, django says
?: (urls.W001) Your URL pattern '^$' uses include with a regex ending with a '$'. Remove the dollar from the regex to avoid problems including URLs.
Is there any good way to use url domain.com/ in website-app/urls.py ,
Not in myproject/urls.py?
This should work
myproject/urls.py
urlpatterns = [
url(r'^', include('website-app.urls', namespace='website')),
]
website-app/urls.py
urlpatterns = [
url(r'$', views.somedef, name='somename')
]

Django "homepage" app urls.py issue

I am pretty new to Django and when I laid my site out I did it in the following way:
The project is a "portal" of sorts,
App 1 "home" is the app that houses the homepage, login, registration
and other "site-wide" functionality
App 2 "inventory" is a basic asset inventory
App 3 "dashboard" is a set of status dashboards based on assets in the inventory
Right now I am trying to add the login functionality and I have a main project urls.py that looks like this:
File: /portal/urls.py
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', include('home.urls'), name='home'),
url(r'^admin/', include(admin.site.urls), name='admin'),
url(r'^inventory/', include('inventory.urls'), name='inventory'),
url(r'^dashboard/', include('dashboard.urls'), name='dashboard'),
url(r'^capacity/', include('capacity.urls'), name='capacity'),
)
My plan is to use the inclusion of .../home/urls.py to manage any site-wide functionality such as logging in, registering, etc.
Right now the home index view shows just fine, but anything else in .../home/urls.py gives me a 404
File: /home/urls.py
from django.conf.urls import patterns, url
from home import views
urlpatterns = patterns('',
url(r'^test/$', views.index, name='home_test'),
url(r'^ajax_login/$', views.ajax_login, name='ajax_login'),
url(r'^$', views.index, name='home_index'),
)
At this point I suppose my question is two-fold: Am I approaching this correctly? If so, how can I get the desired functionality? If not, how should I change the way things are set up/laid out to do it the correct "best practices" way?
Thanks in advance!
EDIT
Got it working thanks to dt0xff and holdenweb, accepted holdenweb's answer since it was more accurate including the need to put the home url inclusion below the rest.
Here is my new portal/urls.py file for reference
File: /portal/urls.py
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls), name='admin'),
url(r'^inventory/', include('inventory.urls'), name='inventory'),
url(r'^dashboard/', include('dashboard.urls'), name='dashboard'),
url(r'^capacity/', include('capacity.urls'), name='capacity'),
url(r'^', include('home.urls'), name='home'),
)
The issue is with your first pattern, which will only match the empty URL. So any empty URL will cause the home/urls.py URLs to be analyzed, but only the empty one will match even in that.
Unfortunately if there is no common prefix then that pattern "^" will match every URL (since they all start at the beginning ...).
So you should either use a common prefix for all the pages, or put the home URL specification at the end to give the other URLs a chance to match before it is tested.
Django looks in urls like this:
Get list of root urls - portal/urls
Find first, which matches to current url
If it is include, go to included urls, cutting off matched part
Your problem is here
url(r'^$', include('home.urls'), name='home'),
I mean, here
'^$'
You want url to match "start and then end of url". It works good with root(dunno.com/), but not with others, because url will contain something more...
So, just remove $ and you are fine
url(r'^', include('home.urls'), name='home'),
you never need to add regex($) at project/urls.py

Categories

Resources