[Fixed]-How do you create a Django HttpRequest object with the META fields populated?

27👍

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!

0👍

in case of someone need to parse an Ajax request and call it immediately in some view:

def ajaxRequest(di=None, request=None) -> HttpRequest:
    def is_ajax(self):
        return True
    if request:
        r = request
    else:
        r = HttpRequest()
    r.is_ajax = is_ajax.__get__(r)
    if di:
        for kk, vv in di.items():
            setattr(r, kk, vv)
    return r

this allow you to do:

@csrf_exempt
def messageReadPost(request):
    if request.is_ajax() and request.method == 'POST':
        if not request.user.is_authenticated:
            # ...

@login_required
def chatFriendsView(request):
    # ...
    messageReadPost(ajaxRequest(request=request, di={
        'method': 'POST', 
        'POST': {'other': p.pk}
    }))

Leave a comment