我目前正在开发一个基于Django框架的项目,该框架需要构建API,除了可以接收GET请求的一个或两个之外,只接受POST请求。
其中一个apis,比如/ x /,是在方法类型为POST的表单提交时调用的。附加到此api / x /的视图修改了请求,然后需要调用另一个API(例如/ y /)或仅再次接受POST请求的视图。
我的代码如下:
views.py
from django.template import RequestContext
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
import logging
#print "__name__ : " + __name__
logger = logging.getLogger('django.request')
logger_info = logging.getLogger('correct_info')
#to_be_commented
@api_view(['POST','GET'])
def load_filter(request):
context = RequestContext(request)
if request.method == 'POST':
print request.data
filter_list = request.POST.getlist('profile')
print filter_list
stdd_filters = ['gender','state','country','examEnrolled','examDefault','examSelected']
profFilters = {}
#profFilters['filters'] = {}
for flter in stdd_filters:
if flter in filter_list:
profFilters[flter] = request.POST.getlist(flter)
else:
profFilters[flter] = []
print profFilters
if not request.POST._mutable:
request.POST._mutable = True
request.POST['filters'] = profFilters
if 'AND' in request.data:
print "TRUE AND"
**#problem here**
#return redirect('profile_filter_and')
return HttpResponseRedirect('../filtered/and/')
elif request.method == 'GET':
return render(request,"filters.html",{})
@api_view(['POST'])
def profile_filter_and(request):
if request.method == POST:
#entire code
我已经尝试了重定向和HttpResponseRedirect方法,但是他们都将url或视图函数调用为GET请求,因此我收到以下错误:
HTTP 405 Method Not Allowed
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept
{
"detail": "Method \"GET\" not allowed."
}
虽然我希望将重定向作为POST请求重定向到url或视图,因为它只接受POST请求。我曾尝试在互联网上搜索相同内容,但没有任何成果。我是Django开发API的初学者。
答案 0 :(得分:2)
"我尝试了重定向和HttpResponseRedirect方法,但他们都将url或视图函数称为GET"
这是因为重定向POST数据被认为是糟糕的设计选择,Django不支持任何显而易见的方式。查看类似问题的答案:
https://stackoverflow.com/a/3024528/4400065
解决问题的一个简单方法是将数据传递给函数,而不是发送antoher HTTP请求。