What takes priority of urls out of Django and AngularJS? - django

I am using Django with Angular... When I refresh my pages, I would prefer Angular to handle routing. So I need to render layout.html (via django), and after that let Angular manage the urls and routing to the correct controller.
For example in Django:
urls.py:
urlpatterns = patterns('',
url(r'^api/', include(v1_api.urls)),
url(r'^.*$', 'home.views.index'),
)
views.py
def index(request):
return render(request, 'layout.html', {})
But the priority of Django is not according to the number of lines written. Because now after refreshing, the urls that start with api, render index as well. It means Django didn't understand that the urls that start by api have higher priority.
So, whats priority of urls in Django, and has using Angular changed this?

Django will always return the first matching pattern.
i found the solution:
in url.py i changed reg-exp, instead of
url(r'^.*$', 'home.views.index'),
i used :
url(r'^.*/$', 'home.views.index'),
now if Django didn't find any matches, shows index.

Related

Django: URL Path not found jumps into next app

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.
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')),
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.

How to make dynamic URLs with Django

my new project needs to fetch URLs from database. Example:
Backend add Categorys and URLs should work like:
www.example.com/hardware
if I make in Backend a new subcategory:
www.example.com/hardware/notebooks
If I add a article:
ww.example.com/hardware/notebooks/lenovo-e410 or articlenumbers.
But I didnt find out where I can add urls from SQL Queries.
But I didnt find out where I can add urls from SQL Queries.
You don't need to; You should create fixed patterns after your dynamic urls.
So in your urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('/<str:category>/', views.hardware),
path('/<str:category>/<str:subcategory>/', views.subcategory),
path('/<str:category>/<str:subcategory>/<str:article>/', views.areticle),
]
or if you prefer to just have urls for your arricles, remove the first two patterns.
Then in the corresponding views for each pattern, you should look up your database for the urls.
I think you haven't gone through Django tutorial, I request you to go through the tutorial given at https://docs.djangoproject.com/en/3.0/intro/tutorial01/#write-your-first-view
Add the following pattern to urls.py
# urls.py
from django.urls import path
urlpatterns = [
path('/<str:category>/<str:product>/'),
]
# views.py
def product_page_view(request, category, product):
# ... your stuffs
Read about Django URLs at https://docs.djangoproject.com/en/3.0/topics/http/urls/

Different URL config depending on domain in Django

In Mezzanine there are two different URLs that you could use depending what content you want to be displayed. Is there a way to check inside the urls.py if the active domain is on a subdomain or just the "regular" domain?
This is the two different styles:
url('^$', direct_to_template, {'template': 'index.html'}, name='home'),
url('^$', mezzanine.blog.views.blog_post_list, name='home'),
I haven't found a solid way for this yet. I want to display blog_post_list if I am on a subdomain (wildcard / e.g. sub.example.com) and index.html if I am on the "main" domain (e.g. example.com)
No, the urls.py is loaded when your app boots up and only looks at the path. The current URL is part of the request objects, that the Middleware and the View receives.
However, you could use a view to delegate the request, based on the URL path.
url('^$', my_view, name='home')
And the view could use the current request object to delegate to one of the two subsequent views.
def my_view(request):
if 'something' in request.META['HTTP_HOST']:
return something_view(request)
else:
return another_view(request)
However, there is an app to do what you want to do, django-hosts. It allows to load different urls.py files based on the host.
from django_hosts import patterns, host
host_patterns = patterns('path.to',
host(r'api', 'api.urls', name='api'),
host(r'beta', 'beta.urls', name='beta'),
)

django registration not loading the registration_complete.html template

I am using Django 1.3 and django-registration 0.8. I am trying to use the RegistrationFormUniqueEmail class to enforce unique emails.
The form validation works but once the form is submitted, it does not load the registration_complete.html template. The page refreshes, and the url goes to register/complete, but it just displays an empty registration_form.html template.
I suspect my urls.py is incorrectly configured:
from registration.forms import RegistrationFormUniqueEmail
urlpatterns = patterns('',
url(r'^accounts/register/', 'registration.views.register', {'form_class':RegistrationFormUniqueEmail,'backend':'registration.backends.default.DefaultBackend' }),
url(r'^accounts/', include('registration.urls')),
Any suggestions? I'd prefer not to upgrade Django.
Try adding a $ to the end of your first regex. At the moment, it matches both /accounts/register/ and /accounts/register/complete/.
url(r'^accounts/register/$', 'registration.views.register', {'form_class':RegistrationFormUniqueEmail,'backend':'registration.backends.default.DefaultBackend' }),

What's the best way to map the main urls in a django project?

I've got a django project that contain some apps. The main urls.py includes the urls.py from the apps I've enabled, and all is good.
Now I want to configure the project so that when you go to http://testsite/, you'll get the same page that you get when you go to http://testsite/app/.
I can do this by duplicating the corresponding line in the apps urls.py in the projects urls.py, but this feels dirty.
Anyone know a better way?
Set up a redirect_to from the first url to the second, ie:
from django.conf.urls.defaults import patterns, url, include
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
# Example:
url(r'^$', redirect_to, {'url':'/app/'}),
url(r'^app/', include('app.urls')),
# ...
)
HTH
A redirect is the way to go, because you don't want multiple canonical URLs for the same resource (wastes Google juice). Ideally, you should do the redirect as close to the edge of your stack as possible to conserve server resources. So you can do a Django redirect_to urlconf entry, but you'd be better off with an Apache or nginx or insert-your-webserver-here redirect, so the initial request never has to hit Django at all.