Problem
I’d like to render an arbitrary view, by calling the view (capture the response and extract the rendered content), to a string, inside another view.
The problem being I’d like to have a dummy user “logged-in” during the rendering of that view, along with changing a few other minor things in the request.
What I’d like to avoid is building a request completely from scratch, as 90% of the request I’ll have at hand in the parent view will be the same.
I’m wondering how I should go about this as far as best practice is concerned, as well as technically?
I’m currently thinking something like this: (But I can’t help but feel this is horrible and there’s got to be a better way, I just cannot think of it)
View stuff…
Log current user out
Create/Login dummy user
Somehow modify request a bit
Render view to string
Log out dummy user
Log back in original user
End of view stuff…
Any ideas? Or a pointer into a better direction?
Thanks,
dennmat
You don’t actually need to log the current user out, you could just change the user in the
HttpRequestobject you plan to use to render the other view. You could do something like this:If you need to login your dummy user you could use
django.contrib.auth.authenticateor ordjango.contrib.auth.loginto do so. Example usinglogin(avoids necessity of using dummy user’s password):