Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question related to reverse function and kwargs

Tags:

python

django

To reverse lookup an url by means of name or View_name we will use reverse function in the views like below

reverse("calendarviewurl2", kwargs={"year":theyear,"month":themonth})

and reverse function signature is as follows

http://code.djangoproject.com/browser/django/trunk/django/core/urlresolvers.py

def reverse(self, lookup_view, *args, **kwargs)

My question is related to kwargs

when we want to send a dictionary as keyword arguments we should use the below syntax snippet 1

 kwargs={"year":2009,"month":9}
   reverse("name",**kwargs)

as opposed to below code
snippet 2

  reverse("name",kwargs={"year":2009,"month":9})

So my question is

  1. Do the snippet1 and snippet2 are same? ( i feel they are not same)
  2. In case of reverse function only snippet 2 is working where as snippet 1 is not properly working.Why is it so? (Even though the proper way to send a dictionary is by using syntax mentioned in snippet1.)
like image 261
Rama Vadakattu Avatar asked Sep 30 '09 10:09

Rama Vadakattu


1 Answers

Didn't you look at the signature,

def reverse(viewname, urlconf=None, args=None, kwargs=None, 
                      prefix=None, current_app=None):

takes no **kwargs at all.

kwargs={"year":2009,"month":9}
reverse("name",**kwargs)

means

reverse("name", year=2009, month=9)

which is completely different from

reverse("name",kwargs={"year":2009,"month":9})

When a function actually does take **kwargs, both ways to call it are the same. But that's not the case here. Reverse would have look like this to take **kwargs:

def reverse(viewname, urlconf=None, prefix=None, 
                      current_app=None, *args, **kwargs):
like image 188
Jochen Ritzel Avatar answered Oct 05 '22 23:10

Jochen Ritzel