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
?
From Django Docs. Request came from User that want to load page. When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function.
Django REST framework introduces a Request object that extends the regular HttpRequest, this new object type has request. data to access JSON data for 'POST', 'PUT' and 'PATCH' requests. However, I can get the same data by accessing request. body parameter which was part of original Django HttpRequest type object.
request.stream returns a stream representing the content of the request body. You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior. As REST framework's Request extends Django's HttpRequest, all the other standard attributes and methods are also available.
request.user typically returns an instance of django.contrib.auth.models.User, although the behavior depends on the authentication policy being used. If the request is unauthenticated the default value of request.user is an instance of django.contrib.auth.models.AnonymousUser. For more details see the authentication documentation.
As REST framework's Request extends Django's HttpRequest, all the other standard attributes and methods are also available. For example the request.META and request.session dictionaries are available as normal.
If the request is unauthenticated the default value of request.user is an instance of django.contrib.auth.models.AnonymousUser. For more details see the authentication documentation. request.auth returns any additional authentication context.
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.")
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