156π
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
138π
As of Django 1.5, this can be accessed from the request object
current_url = request.resolver_match.url_name
If you would like the url name along with the namespace
current_url = request.resolver_match.view_name
- [Django]-Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
- [Django]-Django Rest Framework: Dynamically return subset of fields
- [Django]-How to get form fields' id in Django
35π
For those who namespace their url patterns, then you may be interested in the namespaced url name of the request. In this case, Django called it view_name
instead.
request.resolver_match.view_name
# return: <namespace>:<url name>
- [Django]-How to delete project in django
- [Django]-Django ManyToMany filter()
- [Django]-Django REST Framework custom fields validation
- [Django]-Django switching, for a block of code, switch the language so translations are done in one language
- [Django]-Dynamically adding a form to a Django formset
- [Django]-Django edit user profile
- [Django]-Table thumbnail_kvstore doesn't exist
- [Django]-Constructing Django filter queries dynamically with args and kwargs
- [Django]-.filter() vs .get() for single object? (Django)
4π
Clarification of the question: βIn a view, how do you get the name of a urlpattern that points to it, assuming there is exactly one such urlpattern.β
This may be desirable for the reasons stated: from within the view, we want a DRY way of getting a url to the same view (we donβt want to have to know our own urlpattern name).
Short answer: Itβs not really simple enough to teach your class, but it might be a fun thing for you to do in an hour or two and throw up on GitHub.
If you really wanted to do this, you would have to subclass RegexURLResolver and modify the resolve method to return the matched pattern (from which you can get the pattern name) instead of the view and keyword/value pairs.
http://code.djangoproject.com/browser/django/trunk/django/core/urlresolvers.py#L142
You could then create a decorator or perhaps more appropriately middleware that uses this subclass to get the pattern name and store that value somewhere in the request so that views can use it.
If you actually want to do that and you run across some trouble, let me know and I can probably help.
For your class, I would just have them hardcode the pattern name in the view or template. I believe this is the acceptable way of doing it.
Update:
The more I think about this, the more I would discourage trying to get a urlpattern name in a view. urlpattern parameters are fairly independent of the parameters of the view they point to. If you want to point to a certain url, you need to know how the urlpattern works, not just how the view works. If you need to know how the urlpattern works, you might as well have to know the name of the urlpattern.
- [Django]-Iterating over related objects in Django: loop over query set or use one-liner select_related (or prefetch_related)
- [Django]-Django check if a related object exists error: RelatedObjectDoesNotExist
- [Django]-How do I deploy Django on AWS?
2π
To get the absolute URL do like so:
request.build_absolute_uri()
If you want to add something extra at the end of the main ur (not current URL) do as follows:
request.build_absolute_uri("/something/")
If you want to get the only main domain URL do as below:
request.build_absolute_uri("/")
- [Django]-Aggregate() vs annotate() in Django
- [Django]-Django-allauth: Linking multiple social accounts to a single user
- [Django]-Redirect to named url pattern directly from urls.py in django?
1π
- [Django]-How to make the foreign key field optional in Django model?
- [Django]-Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty
- [Django]-CSV new-line character seen in unquoted field error
1π
Itβs a little unclear from your question, but http://docs.djangoproject.com/en/dev/topics/http/urls/ will likely provide an explanation to what youβre after.
Especially useful to note how Django processes requests:
When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute:
- Django determines the root URLconf module to use. Ordinarily, this is the value of the ROOT_URLCONF setting, but if the incoming HttpRequest object has an attribute called urlconf (set by middleware request processing), its value will be used in place of the ROOT_URLCONF setting.
- Django loads that Python module and looks for the variable urlpatterns. This should be a Python list, in the format returned by the function django.conf.urls.defaults.patterns().
- Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
- Once one of the regexes matches, Django imports and calls the given view, which is a simple Python function. The view gets passed an HttpRequest as its first argument and any values captured in the regex as remaining arguments.
If youβre just after the full path, you can try:
http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.get_full_path
I hope that helps β it indicates how to use the URLconf module, and hopefully will help point you in the right direction.
- [Django]-Django TypeError: get() got multiple values for keyword argument 'invoice_id'
- [Django]-__init__() got an unexpected keyword argument 'mimetype'
- [Django]-Django-debug-toolbar not showing up
0π
For example, my_app1
and index
are set to app_name
and name
respectively in my_app1/urls.py
as shown below:
# "my_app1/urls.py"
from django.urls import path
from . import views
app_name = "my_app1" # Here
urlpatterns = [ # Here
path('', views.index, name="index")
]
Then, you can get a URL namespace and it separately in my_app1/views.py
as shown below:
# "my_app1/views.py"
from django.shortcuts import render
def index(request):
print(request.resolver_match.view_name) # my_app1:index
print(request.resolver_match.app_name) # my_app1
print(request.resolver_match.url_name) # index
return render(request, 'index.html')
Then, you can get a URL namespace and it separately in templates/index.html
as shown below:
{# "templates/index.html" #}
{{ request.resolver_match.view_name }} {# my_app1:index #}
{{ request.resolver_match.app_name }} {# my_app1 #}
{{ request.resolver_match.url_name }} {# index #}
- [Django]-Django migrate βfake and βfake-initial explained
- [Django]-How to add multiple arguments to my custom template filter in a django template?
- [Django]-How to merge consecutive database migrations in django 1.9+?