43326

Redirect after POST django rest framework

Question:

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>

<strong>views.py</strong>:

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

Answer1:

viewsets.ModelViewSet has a method <a href="https://github.com/encode/django-rest-framework/blob/master/rest_framework/mixins.py#L19" rel="nofollow">create</a> that returns Response object. The response object is subtype of Django Response. Hence you can change behavior using <a href="https://github.com/django/django/blob/master/django/http/response.py#L423" rel="nofollow">HttpResponseRedirect</a> 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)

Recommend

  • Carrot2+ElasticSearch Basic Flow of Information
  • Using database with Store Locator on Google Maps API
  • string replace backslash with slash
  • How to deploy web service as a single dll? C#
  • Elmah Does not email in a fire and forget scenario
  • Facebook Login using PHP SDK not working
  • Can an Entity access a Repository?
  • WPF style for buttons
  • Null Pointer Exception in CodeNameone
  • Is there a way that I can manually control the thresholds between various range on choroplethr?
  • How do I get partial cell styling in excel using EPpplus?
  • exception thrown while building the java application using netbeans
  • How to run the linux/x86/shell_bind_tcp payload stand alone?
  • Preventing Internet-accessing-method from delaying a toast popup
  • Upload video and extract thumbnail using Amazon s3
  • Angular not getting response when it's a non-200
  • get value using jquery
  • Carrierwave default image doesn't display
  • Repeatable job for Laravel json api
  • Can I switch the 'connected' user within an sql script that is sourced by mysql?
  • Bulk loading into PostgreSQL from a remote client
  • Gitlab: copy project to other git lab repository
  • integrity constraint violation: NOT NULL check constraint
  • SELECT on JSONField with Django
  • Passing HTTP Post from AWS API GW to Lambda
  • Is there a .NET method equivalent to NETWORKDAYS in Excel?
  • Authorize Attribute Authentication with Postman in Web Api
  • flex tree gets chopped even after using scroll bar
  • concise way of flattening multiindex columns
  • Can a PHP script be scheduled to run at a specific time or after a specific amount of time has expir
  • How to get rgb from transparent pixel in js
  • WPF custom control and direct content support