Django url passing more than one parameter - python

in my django project i create in urls.py file an entry like this one:
....
url(r'^pd/<str:df>/<str:dt>/<int:v_id>/<str:interval>', calc_q),
...
because i need to pass different params to my calc_q function.
Well when i start my django project and try to call my url:
http://127.0.0.1:8000/pd/2021-06-27/2021-06-29/17/15min/
i get an error:
...
^pd/str:df/str:dt/int:v_id/str:interval
...
The current path, pd/2021-06-27/2021-06-29/17/15min/, didn't match any of these.
Why djngo cannot find my url in url list?
So many thanks in advance

you are mixing the regex syntax that url(…) and re_path(…) [Django-doc] use with the syntax for a path(…) [Django-doc]. You thus work with a path like:
from django.urls import path
urlpatterns = [ScopedTypeVariables
# …,
path('pd/<str:df>/<str:dt>/<int:v_id>/<str:interval>/', calc_q),
# …
]

Related

Django url showed error: unresolved reference

I have a url path in urls.py:
urlpatterns = [
...
url(r'^accounts/', include('allauth.urls')),
...
]
but the url will show: unresolved reference 'url'. Did I miss something to import?
As of Django 2 url() was replaced with path() and re_path(). If you are not using Django 1, you can update your code to use path().
from django.urls import path, include
urlpatterns = [
path('accounts/', include('allauth.urls')),
]
For matching a path with RegEx like the Django 1 url() function you can use re_path() like this...
from django.urls import path, include
urlpatterns = [
re_path(r'^accounts/', include('allauth.urls')),
]
However, because of how simple the path you are trying to match is, I would recommend using path(). It saves to overhead of performing a regular expression match. Use path() over re_path() as much as possible.
You can read more on the official Django documentation. See links below.
Django 3 Documentation
Old Django 1 Documentation
You may be using Django 2.x
For django-1.x, you can not use such path(..)s, and in that case you need to write a regular expression, like:
url(r'^complete/(?P<todo_id>[0-9]+)$', views.completeTodo, name='complete'),
If you are using django-2.x, you probably want to use path(..), like you have.
I believe it may be to do with how you've set up your regex.
For urls, instead of this:
url('complete/<todo_id>', views.completeTodo, name='complete'),
try this:
url(r'^complete/(?P<todo_id>\d+)$', views.completeTodo, name='complete'),
Or incase you want to use [path]
path('complete/<int:todo_id>', views.completeTodo, name='complete'),

Passing parameters through django url error

I have been trying to load my localhost:8000/streamers/1234 however there is a bug in my urls that I cannot seem to fix. Iv tried both patterns below and I keep getting the error:
Django tried these URL patterns, in this order:
^streamers/(?P[0-9]+)/$ [name='streamer']
The current path, streamers/34/, didn't match any of these.
urlpatterns = [
#path(r'^streamers/<int:id>/', views.streamer, name='streamer'),
url(r'^streamers/(?P<id>[0-9]+)/$', views.streamer, name='streamer'),
]
if "views.streamer" is a class based view, use:
path(r'^streamers/<int:id>/', views.streamer.as_view(), name='streamer'),
Notice the "as_view()" after views.streamer.

Cannot use extra_option with path django

I don't understand why I cannot use the path() method as documented here: https://docs.djangoproject.com/en/2.0/topics/http/urls/#passing-extra-options-to-view-functions in my apps urls.py.
Here is the code I have:
from django.conf.urls import url, include
from django.contrib import admin
from django.urls import path
from . import views as AliasViews
from permissions import views as PermissionsViews
urlpatterns = [
...
path(r'^user/(?P<alias_id>\d{1,})/members/?$',
AliasViews.UserAliasMember.as_view(),
name='useralias_member', {'alias_type':'UserAlias'}),
...
]
I get this error: SyntaxError: non-keyword arg after keyword arg.
This has nothing to do with the path function. As the error says, Python syntax does not allow keyword arguments - eg name='useralias_member' - before non-keyword arguments. Your extra dictionary should be before that name argument.
Note however that you're also confusing path with url. The new path function doesn't use regexes, it uses the special <arg:type> format. If you want to use regexes, switch back to url.

Django redirect URL with parameter, inside urls.py file?

I'm using Django 1.9. Is there any way to redirect a URL with a parameter in my urls.py file?
I want to permanently redirect a URL like /org/123/ to the corresponding URL /neworg/123.
I know how to redirect within a view, but I'm wondering if there's any way to do it solely inside urls.py.
You can use RedirectView. As long as the old and new url patterns have the same args and kwargs, you can use pattern_name to specify the url pattern to redirect to.
from django.views.generic.base import RedirectView
urlpatterns = [
url(r'^neworg/(?P<pk>\d+)/$', new_view, name='new_view'),
url(r'^org/(?P<pk>\d+)/$', RedirectView.as_view(pattern_name='new_view'), name='old_view')
]

How to get the url path of a view function in django

As an example:
view.py
def view1( request ):
return HttpResponse( "just a test..." )
urls.py
urlpatterns = patterns('',
url( r'^view1$', 'app1.view.view1'),
)
I want to get the URL path of view1. How can I do this.
I want to avoid hard coding any URL paths, such as "xxx/view1".
You need reverse.
from django.urls import reverse
reverse('app1.view.view1')
If you want to find out URL and redirect to it, use redirect
from django.urls import redirect
redirect('app1.view.view1')
If want to go further and not to hardcode your view names either, you can name your URL patterns and use these names instead.
This depends whether you want to get it, if you want to get the url in a view(python code) you can use the reverse function(documentation):
reverse('admin:app_list', kwargs={'app_label': 'auth'})
And if want to use it in a template then you can use the url tag (documentation):
{% url 'path.to.some_view' v1 v2 %}
If you want the url of the view1 into the view1 the best is request.get_path()
As said by others, reverse function and url templatetags can (should) be used for this.
I would recommend to add a name to your url pattern
urlpatterns = patterns('',
url( r'^view1$', 'app1.view.view1', name='view1'),
)
and to reverse it thanks to this name
reverse('view1')
That would make your code easier to refactor
Yes, of course you can get the url path of view named 'view1' without hard-coding the url.
All you need to do is - just import the 'reverse' function from Django urlresolvers.
Just look at the below example code:
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
def some_redirect_fun(request):
return HttpResponseRedirect(reverse('view-name'))
You can use the reverse function for this. You could specify namespaces and names for url-includes and urls respectively, to make refactoring easier.
Universal approach
install Django extensions and add it to INSTALLED_APPS
Generate a text file with all URLs with corresponding view functions
./manage.py show_urls --format pretty-json --settings=<path-to-settings> > urls.txt
like
./manage.py show_urls --format pretty-json --settings=settings2.testing > urls.txt
Look for your URL in the output file urls.txt
{
"url": "/v3/blockdocuments/<pk>/",
"module": "api.views.ganeditor.BlockDocumentViewSet",
"name": "block-documents-detail",
},

Categories

Resources