I just learnt that with Rails is possible to simulate HTTP requests in the console with few lines of code.
Check out: http://37signals.com/svn/posts/3176-three-quick-rails-console-tips (section "Dive into your app").
Is there a similar way to do that with Django? Would be handy.
You can use
RequestFactory
, which allowsinserting a user into the request
inserting an uploaded file into the request
sending specific parameters to the view
Note that you have to specify both the URL and the view class, so it takes an extra line of code than using
requests
.To set the user of the request, do something like
my_request.user = User.objects.get(id=123)
before getting the response.To send parameters to a class-based view, do something like
response = MyClasBasedView.as_view()(my_request, parameter_1, parameter_2)
Extended Example
Here's an example of using
RequestFactory
with these things in combinationHTTP POST (to url
url
, functional viewview
, and a data dictionarypost_data
)uploading a single file (path
file_path
, namefile_name
, and form field valuefile_key
)assigning a user to the request (
user
)passing on kwargs dictionary from the url (
url_kwargs
)SimpleUploadedFile
helps format the file in a way that is valid for forms.How I simulate requests from the python command line is:
A simple way of simulating requests is:
Update: be sure to launch the django shell (via
manage.py shell
), not a classic python shell.Update 2: For Django <1.10, change the first line to
(See tldr; down)
Its an old question, but just adding an answer, in case someone maybe interested.
Though this might not be the best(or lets say Django) way of doing things. but you can try doing this way.
Inside your django shell
Explanation: I omitted the
reverse()
, explanation being, sincereverse()
more or less, finds the url associated to a views.py function, you may omit thereverse()
if you wish to, and put the whole url instead.For example, if you have a friends app in your django project, and you want to see the
list_all()
(in views.py) function in the friends app, then you may do this.TLDR;