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",
},
Related
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),
# …
]
Hi friends i'm trying to test this urls but i don't how do that, i have the following code but it doesn't work
# Method of the test
def testViewDeleteUserIsResolved(self):
url = reverse('inventory:viewDeleteUser', args={'idUser': tbUser.objects.first().id})
self.assertEquals(resolve(url).func,viewDeleteUser)
# Url to try
path('viewDeleteUser/?P<idUser>[0-9a-f-]+', views.viewDeleteUser, name='viewDeleteUser'),
I don't know what reverse('inventory:viewDeleteUser') stands for. I am also a newbie to Django, but I think it will work if you change it to reverse('viewDeleteUser').
tests.py
from django.urls import reverse
from .views import viewDeleteUser
def testViewDeleteUserIsResolved(self):
url = reverse('viewDeleteUser', args={'idUser': tbUser.objects.first().id})
self.assertEquals(resolve(url).func,viewDeleteUser)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('viewDeleteUser/?P<idUser>[0-9a-f-]+', views.viewDeleteUser, name='viewDeleteUser'),
]
In a Django app you have to create a url.py file where all your urls live, you have to put that path() instruction you have in that file.
Then your function needs to be in the views.py file, also take in count the name of the function has to be the same you're declaring in the path() as far I see you you're using views.viewDeleteUser so in the views.py file you need a function like this:
def viewDeleteUser:
How can I define the URL pattern so that I can pass to an URL as many parameters as I want? I really researched the documentation and other stackoverflow questions but I didn't found something similar to that. I need this to work as a filter for an ecommerce website.
I would like to achieve something like this:
urlpatterns = [
path('test/<str:var1>-<str:var2>/<str:var3>-<str:var4>/...', views.test, name='test'),
]
And in my view function I would define it like that:
def test(request, *args, **kwargs):
# Do whatever you want with kwargs
return HttpResponse('Test')
I think this is a wrong way to make a path, if you want to use it as a filter instead of using it in the path you should use url parameters as a get request.
But if you insist on doing that you can use the Regular expressions 're_path'
# urls.py
from django.urls import path, re_path
from django.conf.urls import url
from myapp import views
urlpatterns = [
re_path(r'^test/(?P<path>.*)$', views.test, name='test'),
# or use url instead it's same thing
url(r'^test/(?P<path>.*)$', views.test, name='test'),
]
Have you considered using query_params?
That is path('test', views.test, name='test')
URL: /test/?filter=asd....
Then access it via the request in the view:
def test(request):
params = request.GET.get('filter', None)
return HttpResponse()
See if you can work out your problem like that :)
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')
]
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"),
]