Suppose I have the following url: /valid/django/app/path/?foo=bar&spam=eggs
I can simulate a request to this url in Django as follows:
from django.shortcuts import render from django.core.urlresolvers import resolve def simulate(request, url=None, template_name="not_important.html"): if url: dv = resolve(url.split('?')[0]) return dv.func(request, *dv.args, **dv.kwargs) else: return render(request, template_name)
However, I would like to include the parameters in the included view so that request.REQUEST and request.GET objects also include foo and spam
I do not understand how I can do this cleanly; as far as I understand the words request.GET and request.REQUEST are immutable, so I canβt just do something like:
import urlparse def simulate(request, url=None, template_name="not_important.html"): if url: dv = resolve(url.split('?')[0]) qs = "".join(url.split('?')[1:]) if qs: request.REQUEST.update(urlparse.parse_qs(qs)) request.GET.update(urlparse.parse_qs(qs)) return dv.func(request, *dv.args, **dv.kwargs) else: return render(request, template_name)
Or I will get an error
This instance of QueryDict is immutable
for the request.GET object and
MergeDict object does not have attribute 'update'
for request.REQUEST object
In case someone wonders why I want to do this: I want to allow users to fill out the form and then when they submit, if they are not logged in, they send them to the login form, which includes the original URL in hidden field. After logging in, instead of redirecting back to this link (this will be a GET request), I want it to call the original view with the request variables that it originally had so that it could use the same POST request.
And therefore, of course, in this process I am also interested in whether it is possible to simulate a POST / GET request in a Django view if it is given a valid URL for the site.