简体   繁体   English

Django收到POST请求后未重定向

[英]Django is not redirecting after receiving a POST request

I'm trying to send some values from the front-end to a Django app. 我正在尝试将一些值从前端发送到Django应用。 I want to manipulate those values and then redirect to another view, but it seems that Django is not redirecting nor rendering nothing. 我想操纵这些值,然后重定向到另一个视图,但是Django似乎既没有重定向也没有呈现任何内容。

This is my urls.py 这是我的urls.py

from django.conf.urls import url
from . import settings
from personality_form import views

urlpatterns = [
    url(r'^$', views.home, name="home"),
    url(r'^apiLogin/(?P<_id>\d+)$', views.apiLogin,name="apiLogin"),
    url(r'^formulario/(?P<_id>\d+)$', views.formulario, name="formulario"),
]

This is my views.py 这是我的views.py

from django.shortcuts import render, redirect
from personality_form.models import *
from personality_form.forms import *
from django.views.decorators.csrf import csrf_exempt

def home(request):  
    return render(request, 'index.html')

def formulario(request, _id):
    if (request.method == 'POST'):
        form = personalityForm(request.POST)
    else:
        form = personalityForm()

    return render(request, 'formulario.html', {'form': form})

@csrf_exempt
def apiLogin(request, _id):
    if (request.method == 'POST'):        
        return redirect('/formulario/'+_id)

And this is the javascript function that I'm using to send the POST request from the front. 这是我用来从前端发送POST请求的javascript函数。

function test() {
            var http = new XMLHttpRequest();
            http.open('POST', '/apiLogin/1234', true);
            http.setRequestHeader('Content-type', 'application/json');
            var payload = {userID: "1234", access: "4567"};
            var params = JSON.stringify(payload);

            // Send request
            http.send(params);
        }

I've tried to send the POST to apiLogin view. 我试图将POST发送到apiLogin视图。 I check that it is entering on that view but when I try to redirect to formulario view, it enters on formulario code but don't seems to execute the render instruction. 我检查它是否在该视图上输入,但是当我尝试重定向到Formulario视图时,它在Formulario代码上输入,但似乎不执行render指令。 I tried to change the redirect function for render but don't show the new html neither. 我尝试更改用于渲染的重定向功能,但均不显示新的html。

Is there a reason why is not redirecting the url and changing the front? 有没有理由不重定向URL并更改前端?

I'm using Django 1.11 and Python 3.6. 我正在使用Django 1.11和Python 3.6。

You have to change your code slightly. 您必须稍微更改代码。 In your api_login() , create a reverse url with an argument. 在您的api_login() ,创建一个带参数的反向URL。 Then inside your JavaScript change the window url itself to redirect. 然后在您的JavaScript内部,更改窗口网址本身以进行重定向。

Firstly, inside your def apiLogin(request, _id) : 首先,在您的def apiLogin(request, _id)

from django.core.urlresolvers import reverse
from django.http import JsonResponse

@csrf_exempt
def apiLogin(request, _id):
    if (request.method == 'POST'):        
        #create a url string using reverse.
        url = reverse('formulario' , kwargs = {'_id' : _id})
        #if the above way doesn't work then try: url = request.build_absolute_uri(reverse('formulario' , kwargs = {'_id' : _id}))
        #Now simply return a JsonResponse. Ideally while dealing with ajax, Json is preferred. 
        return JsonResponse(status = 302 , data = {'success' : url })

Then inside your JavaScript: 然后在您的JavaScript中:

function test() {
    var http = new XMLHttpRequest();
    //The onreadystatechange function is called every time the readyState changes.
    //4: request finished and response is ready
    //basically the below function gets called every time your the response of you request request is returned from the server.
    http.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 302) {
            var json = JSON.parse(this.responseText); 
            console.log(json.success);
            //following line would actually change the url of your window.  
            window.location.href = json.success; 
        }
    };
    http.open('POST', '/apiLogin/1234', true);
    http.setRequestHeader('Content-type', 'application/json');
    var payload = {userID: "1234", access: "4567"};
    var params = JSON.stringify(payload);

    // Send request
    http.send(params);     
}

I hope this works. 我希望这行得通。 If it doesn't then please check what is printed inside the console. 如果没有,请检查控制台内打印的内容。 If it works then simply remove the console statement. 如果可行,则只需删除控制台语句。

Hope this helps. 希望这可以帮助。 Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM