How do I get the django HttpRequest from a django

2019-02-21 18:57发布

问题:

I'm trying to use the django messages framework to show messages after ModelViewSet.create():

class DomainModelViewSet(ModelViewSet):
    def create(self, request):
        super(DomainModelViewSet, self).create(request)
        messages.success(self.request, "Domain Added.")
        return HttpResponseRedirect(reverse('home'))

But I get:

TypeError: add_message() argument must be an HttpRequest object, not 'Request'.

So, how can use the Django HttpRequest from django rest framework Request?

回答1:

I went thru the source code and found my answer while typing out the question.

Django REST framework has a Request keep the HttpRequest (or at least one compatible with django messages) in a _request property. So, this works:

messages.success(self.request._request, "Domain Added.")