I am submitting a POST request via django form to my Django Rest Framework api.
Here is a snippet of my form:
<form action="{% url 'entry-list' %}" method="POST" class="form" role="form">
{% csrf_token %}
{{form.as_p}}
<div class = "form-group">
<button type="submit" class="save btn btn-default btn-block">Save</button>
</div>
views.py
:
class entry_ViewSet(viewsets.ModelViewSet):
queryset = Entry.objects.all()
serializer_class= EntrySerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,)
def perform_create(self, serializer):
serializer.partial = True
serializer.save(created_by=self.request.user)
I am making a successful POST (and item is created in database), however once I save I go to the url /api/entry/
which shows my api w/Markdown. I'd like to have it go back to a specific url.
Is there a way to customize where the POST
redirect to if successful?
Added Serializer:
class EntrySerializer(serializers.ModelSerializer):
created_by = serializers.ReadOnlyField(source='created_by.username')
class Meta:
model = Entry
fields = '__all__'
def __init__(self, *args, **kwargs):
super(EntrySerializer, self).__init__(*args, **kwargs)
for x in self.fields:
self.fields[x].required = False
viewsets.ModelViewSet
has a method create
that returns Response
object. The response object is subtype of Django Response
. Hence you can change behavior using HttpResponseRedirect
into the create
method. For example:
class entry_ViewSet(viewsets.ModelViewSet):
queryset = Entry.objects.all()
serializer_class= EntrySerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,)
def create(self, request, *args, **kwargs):
response = super(entry_ViewSet, self).create(request, *args, **kwargs)
# here may be placed additional operations for
# extracting id of the object and using reverse()
return HttpResponseRedirect(redirect_to='https://google.com')
def perform_create(self, serializer):
serializer.partial = True
serializer.save(created_by=self.request.user)
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