Is there a way to create an HttpRequest
object in Django that has all of the cgi
META
variables present? I'm attempting to process a view, but can't figure out how to (easily) make the request object. I just want to make sure I'm not making life harder than need be manually copying all the fields from an existing request. This feels like something there'd be an existing solution for, but after several hours of searching, I can't find what I need.
I originally went with Client
and RequestFactory
from django.test
, but these fill the request object with junk data, which causes some of the dynamic fields in my view to render with incorrect values (for example, things like SERVER_NAME
)
Is there a correct way to create a usable HttpRequest object?
META. A dictionary containing all available HTTP headers. Available headers depend on the client and server, but here are some examples: CONTENT_LENGTH – The length of the request body (as a string). CONTENT_TYPE – The MIME type of the request body.
In an HttpRequest object, the GET and POST attributes are instances of django. http. QueryDict , a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably <select multiple> , pass multiple values for the same key.
First, I just want to clarify a couple things in your question:
I'm attempting to process a view
By "process a view", I think you mean that you want to pass an HttpRequest object into your view's functions. This is usually done through a URL dispatcher.
I just want to make sure I'm not making life harder than need be manually copying all the fields from an existing request.
It sounds like you want to create a new HttpRequest object based on an existing request, particularly without messing with the headers. You should look over the django.http.HttpRequest documentation to re-use some of the fields from your existing request's fields. For example, request.META
is a dictionary that can be re-used between request objects.
It seems like your best approach is to use the django.http.HttpRequest object directly. You can create it as follows:
from django.http import HttpRequest
request = HttpRequest()
Then you can set the fields however you like, and request.META
is just an empty dictionary that you can set however you like. For example:
request.method = 'GET'
request.META = myOldRequest.META
request.META['SERVER_NAME'] = 'localhost'
I can let you look up the rest. Hopefully that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With