Reputation: 2355
I am currently working on a project based on Django framework which requires APIs to be built that accept POST requests only except one or two which can receive GET requests.
One of those apis, say /x/, is invoked on the submission of form with method type as POST. The view attached to this api /x/ modifies the request and then needs to invoke another API(say /y/) or view which again accepts POST requests only.
My code is as follows :
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
I have tried both redirect and HttpResponseRedirect methods but both of them call the url or view functions as a GET request due to which I get the following error :
HTTP 405 Method Not Allowed
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept
{
"detail": "Method \"GET\" not allowed."
}
whereas I want the redirection as POST request to the url or view since it accepts only POST requests. I have tried searching about the same on Internet but haven't got anything fruitful. I am a beginner in developing APIs in Django.
Upvotes: 0
Views: 2099
Reputation: 4512
"I have tried both redirect and HttpResponseRedirect methods but both of them call the url or view functions as a GET"
This is because redirecting POST data is considered bad design choice and is not supported by Django in any obvious way. Check out this answer to similar question:
https://stackoverflow.com/a/3024528/4400065
One simple solution to your problem would be passing data to function, instead of sending antoher HTTP request.
Upvotes: 2