我通过django表单向我的Django Rest Framework api提交POST请求。
以下是我的表单片段:
<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)
我正在成功发布POST(并且项目是在数据库中创建的),但是一旦我保存,我会转到显示我的api w / Markdown的网址/api/entry/
。我想让它回到一个特定的网址。
有没有办法自定义POST
重定向到哪里成功?
添加了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
答案 0 :(得分:9)
viewsets.ModelViewSet
有一个返回Response
对象的方法create
。响应对象是Django Response
的子类型。因此,您可以使用HttpResponseRedirect
将行为更改为create
方法。例如:
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)