Auto GET to argument of view
-
11-09-2019 - |
Question
some_view?param1=10¶m2=20
def some_view(request, param1, param2):
Is such possible in Django?
Solution
You could always write a decorator. Eg. something like (untested):
def map_params(func):
def decorated(request):
return func(request, **request.GET)
return decorated
@map_params
def some_view(request, param1, param2):
...
OTHER TIPS
I'm not sure it's possible to get it to pass them as arguments to the view function, but why can't you access the GET
variables from request.GET
? Given that URL, Django would have request.GET['param1']
be 10 and request.GET['param2']
be 20. Otherwise, you'd have to come up with some kind of weird regular expression to try and do what you want.
I agree with Paolo... the stuff after the '?' are GET parameters and should probably be treated as such. That said, if you really want to keep the definition of some_view() as you've stated in the question, you could do something like:
from django.http import Http404
def some_view_proxy(request):
if 'param1' in request.GET and 'param2' in request.GET:
return some_view(request, request.GET['param1'],
request.GET['param2'])
raise Http404
Or you could just define some_view() like this and use the GET params. Just curious, why do you want that?
Instead of fighting Django, why not just request some_view/10/20 and then set up urls.py to extract the arguments?