Cannot use extra_option with path django - python

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.

Related

How one can capture string that contain one or more forward slash in django urls

my code look like this
urls.py:
from django.urls import path
from. import views
app_name ='graduates'
urlpatterns = [
.
.
path('status_detail/<str:id>/', views.status_detail, name='status_detail'),
]
views.py:
def status_detail(request, id):
return HttpResponse(id)
then I wanna use it like this somewhere in my code
And it works fine for strings those don't contain forward slash.
But I want to pass id of student to urls that look like this
A/ur4040/09, A/ur5253/09 and etc
Please help me how could I do this
We can use default Path converters available in django
path('status_detail/<path:id>/', views.status_detail, name='status_detail'),
path - Matches any non-empty string, including the path separator, '/'.
Try changing your url into a regex:
url(r'^status_detail/(?P<str:id>\w+)/', views.status_detail, name='status_detail')
If url doesn't work because you have urls with same structure, use re_path:
re_path(r'^status_detail/(?P<str:id>\w+)/', views.status_detail, name='status_detail')
Don't forget to import re_path:
from django.urls import path, re_path, include
I hope this solves your problem.

Django url passing more than one parameter

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),
# …
]

urls error in django 1.11.x upgrade to 2.0

I am migrating my project from django 1.11.x to 2.0. I have everything going well till I got to urls. I happen to have an import like this
from cashondelivery.dashboard.app import application as cod_app
and I have my url pattern as
url(r'^dashboard/cod/', include(cod_app.urls)),
but I got the following error in my terminal
url(r'^dashboard/cod/', include(cod_app.urls)),
File ".../dev/lib/python3.6/site-packages/django/urls/conf.py", line 27, in include
'provide the namespace argument to include() instead.' % len(arg)
django.core.exceptions.ImproperlyConfigured: Passing a 3-tuple to include() is not supported. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead.
I would really appreciate a fix.
cashondelivery->dashboard->app
import django
from django.conf.urls import url
from django.contrib.admin.views.decorators import staff_member_required
from oscar.core.application import Application
from . import views
class CashOnDeliveryDashboardApplication(Application):
name = None
default_permissions = ['is_staff', ]
list_view = views.TransactionListView
detail_view = views.TransactionDetailView
def get_urls(self):
urlpatterns = [
url(r'^transactions/$', self.list_view.as_view(),
name='cashondelivery-transaction-list'),
url(r'^transactions/(?P<pk>\d+)/$', self.detail_view.as_view(),
name='cashondelivery-transaction-detail'),
]
if django.VERSION[:2] < (1, 8):
from django.conf.urls import patterns
urlpatterns = patterns('', *urlpatterns)
return self.post_process_urls(urlpatterns)
application = CashOnDeliveryDashboardApplication()
You need to drop the include() and just pass the urls directly:
url(r'^dashboard/cod/', cod_app.urls),
The urls property returns a 3-tuple, not a list of urlpatterns, and support for passing this to include() was dropped in Django 2.
In django2 its path for normal url and re_path for url using regex.
path('dashboard/cod/', include(cod_app.urls)),

How to redirect url pattern with variables from urls.py in Django?

I'd like to redirect url pattern with variables from urls.py.
I refer other stackoverflow solution, but I don't know when url having a variable like following code.
from django.conf.urls import patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns(
url(
r'^permalink/(?P<id>\d+)/foo/$',
RedirectView.as_view(url='/permalink/(?P<id>\d+)/')
),
)
With this code, django will redirect /permalink/1/foo/ to /permalink/(?P<id>\d+)/, not the /permalink/1/.
Is there any solution without using views.py?
Of course I know solution using controller, but I wonder is there any simpler solution with using url pattern.
Passing url='/permalink/(?P<id>\d+)/' to RedirectView will not work, because the view does not substitute the named arguments in the url.
However, RedirectView lets you provide the pattern_name instead of the url to redirect to. The url is reversed using the same args and kwargs that were passed for the original view.
This will work in your case, because both url patterns have one named argument, id.
urlpatterns = [
url(r'^permalink/(?P<id>\d+)/foo/$',
RedirectView.as_view(pattern_name="target_view"),
name="original_view"),
url(r'^permalink/(?P<id>\d+)/$', views.permalink, name="target_view"),
]
If the target url pattern uses other arguments, then you can't use url or pattern_name. Instead, you can subclass RedirectView and override get_redirect_url.
from django.core.urlresolvers import reverse
from django.views.generic import RedirectView
class QuerystringRedirect(RedirectView):
"""
Used to redirect to remove GET parameters from url
e.g. /permalink/?id=10 to /permalink/10/
"""
def get_redirect_url(self):
if 'id' in self.request.GET:
return reverse('target_view', args=(self.request.GET['id'],))
else:
raise Http404()
It would be good practice to put QuerystringRedirect in your views module. You would then add the view to your url patterns with something like:
urlpatterns = [
url(r'^permalink/$', views.QuerystringRedirect.as_view(), name="original_view"),
url(r'^permalink/(?P<id>\d+)/$', views.permalink, name="target_view"),
]

Django URLconf: How to use captured params in include's RedirectView?

I have a parent URLconf:
from django.conf.urls import include, patterns, url
urlpatterns = patterns('',
(r'^main/(?P<name>[^/]+)/(?P<region>[^/]+)/(?P<id>[^/]+)/', include('foo')),
)
And a child URLconf (included in the parent) that includes a redirect:
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^view/$', RedirectView.as_view(url='/main/%(name)s/%(region)s/%(id)s/detail')),
)
(Essentially, I'm trying to redirect a path that looks like /main/product/1/134/view to a path that looks like /main/product/1/134/detail.)
The Django documentation says that "An included URLconf receives any captured parameters from parent URLconfs."
But when I try access /main/product/1/134/view, I get a KeyError because name isn't recognized.
Is there some other way that I have to reference the received captured parameters in the RedirectView?
Note: I don't get an error when I do the whole thing in the parent URLconf:
urlpatterns = patterns('',
(r'^main/(?P<name>[^/]+)/(?P<region>[^/]+)/(?P<id>[^/]+)/view/$', RedirectView.as_view(url='/main/%(name)s/%(region)s/%(id)s/detail'))
)
This section of the docs suggests that you should be using two percent signs instead of one:
The given URL may contain dictionary-style string formatting, which will be interpolated against the parameters captured in the URL. Because keyword interpolation is always done (even if no arguments are passed in), any "%" characters in the URL must be written as "%%" so that Python will convert them to a single percent sign on output.
So in your case, try:
url(r'^view/$', RedirectView.as_view(url='/main/%%(name)s/%%(region)s/%%(id)s/detail')),
It might be cleaner to use the pattern_name argument instead of url. The args and kwargs will be used to reverse the new url.
url(r'^view/$', RedirectView.as_view(pattern_name='name_of_url_pattern_to_redirect_to')),

Categories

Resources