I have to build an url dynamically according to the current url. Using the {% url %}
tag is the easiest way to do it, but I need the current url name to generate the new one dynamically.
How can I get the url name attached to the urlconf that leads to the current view?
EDIT : I know I can manually handcraft the url using get_absolute_url
but I'd rather avoid it since it's part of a lecture and I would like to demonstrate only one way to build urls.
The students know how to use {% url %}
. They are know facing a problem when they have to generate a more complete url based on the current one. The easiest way is to use {% url %}
again, with some variations. Since we have named url, we need to know how to get the name of the url that called the current view.
EDIT 2: another use case is to display parts of the base template différently according to the base template. There are other ways to do it (using CSS and {% block %}, but sometime it just nice to be able to remove the tag of the menu entry of base.html if the viewname match the link.
Run the following command to start the Django server. Execute the following URL from the browser to display the domain name of the current URL. The geturl1() function will be called for this URL that will send the domain name to the index. html file.
The name is used for accessingg that url from your Django / Python code. For example you have this in urls.py url(r'^main/', views.main, name='main') Now everytime you want to redirect to main page, you can say redirect('app.main')
To get the full or absolute URL (with domain) in Python Django, we can use the build_absolute_uri method. to call request. build_absolute_uri with reverse('view_name', args=(obj.pk, ) to get the path of the view with reverse .
I don't know how long this feature has been part of Django but as the following article shows, it can be achieved as follows in the view:
from django.core.urlresolvers import resolve current_url = resolve(request.path_info).url_name
If you need that in every template, writing a template request can be appropriate.
Edit: APPLYING NEW DJANGO UPDATE
Following the current Django update:
Django 1.10 (link)
Importing from the
django.core.urlresolvers
module is deprecated in favor of its new location,django.urls
Django 2.0 (link)
The
django.core.urlresolvers
module is removed in favor of its new location,django.urls
.
Thus, the right way to do is like this:
from django.urls import resolve current_url = resolve(request.path_info).url_name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With