Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect after POST django rest framework

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     
like image 851
TangoAlee Avatar asked Oct 23 '17 16:10

TangoAlee


1 Answers

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)
like image 184
Abbasov Alexander Avatar answered Nov 18 '22 06:11

Abbasov Alexander