Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a Django HttpRequest object with the META fields populated?

Tags:

python

django

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?

like image 648
user3308774 Avatar asked Jan 28 '15 00:01

user3308774


People also ask

What is request Meta in Request object in Django?

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.

What is QueryDict Django?

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.


1 Answers

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!

like image 186
modulitos Avatar answered Sep 27 '22 22:09

modulitos