如何使用Ajax和Django进行重定向?

时间:2019-05-25 14:52:51

标签: javascript python ajax django

我有一个表单,可以在db中创建新记录。由于ajax而起作用。我有参数'id',当创建新记录时(在填写表格之后),该参数会自动创建。我想使用此ID,因为当用户填写表单或只是在页面中打印此链接时,我需要将用户重定向到页面/127.0.0.1:8000/ 。我该怎么办?

views.py

def add_new(request):
    """ Function which upload new file to UploadModel. """

    form_upload = UploadForm(request.POST, request.FILES, prefix='upload_form')
    if form_upload.is_valid() and request.is_ajax():
        new_file = form_upload.save(commit=False)
        if request.user.is_authenticated:
            new_file.author = request.user
        new_file.created_date = date.today()
        new_file.is_worked = True
        if new_file.ended_date <= date.today():
            new_file.is_worked = False
            new_file.delete()
        else:
            new_file.is_worked = True
        new_file.save()
        return redirect('index')
    form_upload = UploadForm()
    return render(request, 'sharing/index.html', {'form_upload': form_upload})

js文件

function upload(event) {
    event.preventDefault();
    var data = new FormData($('form').get(0));

    $.ajax({
        url: $(this).attr('data-url'),
        type: $(this).attr('method'),
        data: data,
        cache: false,
        processData: false,
        contentType: false,
        success: handleSuccess(),
    });
    return false;
}

function handleSuccess(){
    $("form")[0].reset();
    alert('Success uploading!');
    window.location.href = '/';

}

$(function() {
    $('form').submit(upload);
});

1 个答案:

答案 0 :(得分:0)

import json
from django.http import HttpResponse

def add_new(request):
    """ Function which upload new file to UploadModel. """

    form_upload = UploadForm(request.POST, request.FILES, prefix='upload_form')
    if form_upload.is_valid() and request.is_ajax():
        new_file = form_upload.save(commit=False)
        if request.user.is_authenticated:
            new_file.author = request.user
        new_file.created_date = date.today()
        new_file.is_worked = True
        if new_file.ended_date <= date.today():
            new_file.is_worked = False
            new_file.delete()
        else:
            new_file.is_worked = True
        new_file.save()
        response_data = {}
        response_data['form_upload'] = UploadForm()
        return HttResponse(json.dumps(response_data),content_type="application/json")