[Answer]-Getting a request object as in a view function but called from `manage.py shell`

1👍

Since your goal is to “replicate a request object and fiddle with it from the shell for introspection“, the easiest way to accomplish fiddling with the request object is to use a debugger.

Copy paste the following into your view and reload it:

import pdb; pdb.set_trace()

Now reload the page pointing at that view & you can use PDB’s debugger commands to exec your stuff. For example, inside a view function you can use p request to print the value of request, and you can also execute standard python code:

(Pdb) path = request.META['USERNAME']
(Pdb) h p
p expression
Print the value of the expression.
(Pdb) p path
'Caspar'
(Pdb) from foo.models import MyUser
(Pdb) MyUser.objects.all()
[<MyUser: Bob: 3.62810036125>, <MyUser: Tim: no rating>, <MyUser: Jim: 2.41014167534>, <MyUser: Rod: 1.35651839383>]

Even better, install ipdb (pip install ipdb), which lets you use the much nicer IPython shell, with fancy colors and tab completion.

Or, if you have no need for a debugger but just want an interactive console, install IPython (pip install ipython) and use the following snippet:

import IPython; IPython.embed()

Note that IPython is a prerequisite for ipdb, so installing ipdb will also install IPython.

👤Caspar

Leave a comment