Gonzalo Dambra
Gonzalo Dambra

Reputation: 980

Django: how to get url path?

I've read something about reverse function but I don't get it.

Two of my urls are calling the same view. In this view I need to decide the context based on the url.

urls.py:

urlpatterns = [
    path('view/', my_view),
    path('edit/', my_view),
]

views.py:

def my_view(request):
    #some code
    if(my_url_path == 'view/'):  #just taking a look
        context = {
            'task': 'view'
        }
    elif(my_url_path == 'edit/'):  #can edit
        context = {
            'task': 'edit'
        }

I don't use two different views for these paths because its code is very extensive and I can save many repeated lines (DRY). They do something very similar and I can adjust these small differences in the template based in the context that the view is sending.

How can I do what I showed in the view? Thanks!

Upvotes: 2

Views: 11348

Answers (2)

grrrrrr
grrrrrr

Reputation: 1425

The best practice would be to break it into two different views and move the common code elsewhere.

But if you want to access the path you can just call request.path_info as documented here

Alternatively you could use a capture group on the url to simplify further, provided the url pattern is unique to others in your urls.py. Something along the following

urls.py:

path('<task>/', my_view, name='my_view'),

views.py

def my_view(request, task):
    context = { 'task': task }

Upvotes: 4

rahul.m
rahul.m

Reputation: 5854

you can try this

urlpatterns = [
    path('view/', my_view, 'first_url'),
    path('edit/', my_view, 'second_url'),
]

in view

from django.urls import resolve


def my_view(request):
   current_url = resolve(request.path_info).url_name

   if(current_url == 'first_url'):  #just taking a look
        context = {
            'task': 'view'
        }
   elif(current_url == 'second_url'):  #can edit
        context = {
            'task': 'edit'
        }

hope it helps

Upvotes: 3

Related Questions