Django 和 ajax 形式。表单运行,但我没有收到确认消息

Posted

技术标签:

【中文标题】Django 和 ajax 形式。表单运行,但我没有收到确认消息【英文标题】:Django and ajax form. Form runs, but I do not get a confirmation message 【发布时间】:2013-11-29 03:06:21 【问题描述】:

我正在尝试创建一个包含两个可以单独提交的 django 表单的页面。我不想在用户提交时重定向用户,并尝试将 ajax 与 django 一起使用来完成带有确认消息而不是外部操作的提交。

这是我的 Forms.py

from django import forms
from django.db import models
from django.forms import ModelForm
from debates.models import Affirmative,Negative

SCORE_CHOICES = (
        ('5','5'),
        ('6','6'),
        ('7','7'),
        ('8','8'),
        ('9','9'),
        ('10','10')
        )
scores = forms.ChoiceField(widget=forms.Radioselect(), choices=SCORE_CHOICES)


class AffirmativeScore(ModelForm):
        SlideShowScore = scores.choices
        Speaker1 = scores.choices
        Speaker2 = scores.choices
        CrossExamination = scores.choices
        Argument = scores.choices
        class Meta:
            model = Affirmative

class NegativeScore(ModelForm):
        SlideShowScore = scores.choices
        Speaker1 = scores.choices
        Speaker2 = scores.choices
        CrossExamination = scores.choices
        Argument = scores.choices
        class Meta:
            model = Negative

Views.py

from django.shortcuts import render, get_object_or_404
from debates.models import Topic,Location,Date,Teacher
from debates.forms import AffirmativeScore,NegativeScore
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect



#get the debate that are on
def judge(request): 
    Submit_form = 'null'
    Affform = AffirmativeScore()
    Negform = NegativeScore()
    if request.method == 'GET':
        Affform = AffirmativeScore()
        Negform = NegativeScore()
    elif request.method == 'POST':
        if 'form_Positive' in request.POST:
            Affform = AffirmativeScore(request.POST)
            Submit_form = 'aff'
            if Affform.is_valid():
                Speaker1 = Affform.cleaned_data.get('Speaker1')
                Speaker2 = Affform.cleaned_data.get('Speaker2')
                CrossExamination = Affform.cleaned_data.get('CrossExamination')
                SlideShowScore = Affform.cleaned_data.get('SlideShowScore')
                Argument = Affform.cleaned_data.get('Argument')
                #return render_to_response(msg)
        elif 'form_Negative' in request.POST:
            Negform = NegativeScore(request.POST)
            Submit_form = 'neg'
            if Negform.is_valid():
                SlideShowScore = Negform.cleaned_data.get('SlideShowScore')
                Speaker1 = Negform.cleaned_data.get('Speaker1')
                Speaker2 = Negform.cleaned_data.get('Speaker2')
                CrossExamination = Negform.cleaned_data.get('CrossExamination')
                Argument = Negform.cleaned_data.get('Argument')
                msg = "The operation has been received correctly."
                print request.POST
                return render_to_response('debates/scoring_upload.html', 'msg':msg, context_instance=RequestContext(request))
                #return render_to_response(msg)
        if request.is_ajax():
            return render(request, 'debates/scoring_upload.html')
            msg = "The operation has been received correctly."
            print request.POST
#Now return the rendered template
            return render_to_response('debates/scoring_upload.html', 'msg':msg, context_instance=RequestContext(request))

    return render(request,'debates/judge.html', 
        'form1':Affform, 'form2':Negform,
    )

def handle(request):

    return render(request,'debates/scoring_upload.html', 
    )

Judge.html

<html>
<head>
<link rel="stylesheet" type="text/css" href="STATIC_URLDebateSite.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">

    jQuery(function() 

        var form = jQuery("Form_Response")
        form.submit(function(e)
            jQuery("#sendbutton").attr('disabled', true)
            jQuery("#sendwrapper").prepend('<span>Sending message, please wait... </span>')
            jQuery("#ajaxwrapper").load(
                form.attr('action') + ' #ajaxwrapper',
                form.serializeArray(),
                function(responseText, responseStatus) 
                    jQuery("#sendbutton").attr('disabled', false)
                

            );
            e.preventDefault();
        );
    );

</script>
</head>
<body>
<div class="Banner">
        Albany High School Freshmen Debates
    </div>

    <br>
    <br>
    <br>
    <br>
    <br>
    <br>


    <div id="Boxes">

        <div id="AffirmativeNegativeDiv">
            <div id="ScoreBox">


                <h1>Affirmative</h1>
                <br>

                    <form method='post'>
                    <div id="ajaxwrapper">
                        % csrf_token %
                        <br>
                        <br>
                        <ul>
                         form1.as_p 
                        </ul>
                        <p id="sendwrapper"><input type='submit' name='form_Positive' value='Submit_Postitive' /></p>
                    </div>
                </form>
            </div>

            <div id="ScoreBoxNeg">

                <h1>Negative</h1>
                <br>
                    <form method='post'>
                    % csrf_token %
                    <br>
                    <br>
                    <ul>
                     form2.as_p 
                    </ul>
                    <input type='submit' name='form_Negative' value='Submit_Negative' />

                </form>
            </div>

        </div>
    </div>
</body>

</html>

【问题讨论】:

【参考方案1】:

在 AJAX 提交的情况下,您有两个返回语句

if request.is_ajax():
    return render(request, 'debates/scoring_upload.html')
    msg = "The operation has been received correctly."
    print request.POST
    #Now return the rendered template
    return render_to_response('debates/scoring_upload.html', 'msg':msg, context_instance=RequestContext(request))

第一个渲染模板而不将消息添加到上下文中。第二个永远无法到达。

【讨论】:

以上是关于Django 和 ajax 形式。表单运行,但我没有收到确认消息的主要内容,如果未能解决你的问题,请参考以下文章

ajax 形式 is_valid 返回 false (django)

Ajax jQuery serialize() & serializeArray() textarea 未以 Django 形式提交

使用 django 和 ajax 显示表单错误

Bootstrap 模式形式的 AJAX 实现(在 Django 上)

Django 管理员添加表单 ajax 调用

django:csrf_token 用于单个页面上的多个表单和 ajax 请求