问题描述
我正在通过Django表单向我的Django Rest Framework api提交POST请求。
I am submitting a POST request via django form to my Django Rest Framework api.
这是我的表单的摘要:
<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
:
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(并且已在数据库中创建项目),但是一旦保存,我将转到URL / api / entry /
,其中显示了我的带有Markdown的api。我想让它返回到特定的URL。
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.
是否可以自定义 POST
重定向到是否成功?
Is there a way to customize where the POST
redirect to if successful?
添加了序列化器:
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
具有方法返回 Response
对象。响应对象是 Django响应
的子类型。因此,您可以使用放入 create
方法。例如:
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)
这篇关于POST django rest框架后重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!