Django - 点击重定向后提交无效表单提交按钮

时间:2012-05-08 21:38:47

标签: ajax django forms submit

我有一个django项目,其中我有一个由ajax加载的div中的表单。

当我提交带有空字段的表单时,它返回显示所需字段的表单。

当我再次点击提交时,它会重定向到表单的操作,而不是重新加载div中的表单并显示错误,就像我第一次提交时一样。

有没有人知道错误可能发生在哪里?我想象在我的django项目中的ajax或view中的某处。

这是第二次提交返回的内容:

{"success": false, "form": "<head>\n\n</head>\n<body>\n<form action=\"/cookbook/createrecipe/\" method=\"POST\" name=\"recipeform\" id=\"createrecipeform\">\n\t<table>\n\t\t<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='c5ea952ee2144b377b375d91b0843c75' /></div>\n\t\t<tr><th><label for=\"id_name\">Name:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input id=\"id_name\" type=\"text\" name=\"name\" maxlength=\"200\" /></td></tr>\n<tr><th><label for=\"id_author\">Author:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input id=\"id_author\" type=\"text\" name=\"author\" maxlength=\"100\" /></td></tr>\n<tr><th><label for=\"id_picture\">Picture:</label></th><td><input type=\"file\" name=\"picture\" id=\"id_picture\" /></td></tr>\n<tr><th><label for=\"id_ingredients\">Ingredients:</label></th><td><ul class=\"errorlist\"><li>This field cannot be null.</li></ul><textarea id=\"id_ingredients\" rows=\"10\" cols=\"40\" name=\"ingredients\"></textarea></td></tr>\n<tr><th><label for=\"id_steps\">Steps:</label></th><td><ul class=\"errorlist\"><li>This field cannot be null.</li></ul><textarea id=\"id_steps\" rows=\"10\" cols=\"40\" name=\"steps\"></textarea></td></tr>\n<tr><th><label for=\"id_prep_time\">Prep time:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input type=\"text\" name=\"prep_time\" id=\"id_prep_time\" /></td></tr>\n<tr><th><label for=\"id_type\">Type:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><select name=\"type\" id=\"id_type\">\n<option value=\"\" selected=\"selected\">---------</option>\n<option value=\"SW\">Sandwich</option>\n<option value=\"AP\">Appetizers</option>\n<option value=\"SD\">Sauces and Dressings</option>\n<option value=\"SS\">Soups and Salads</option>\n<option value=\"VG\">Vegetables</option>\n<option value=\"RG\">Rice, Grains and Beans</option>\n<option value=\"PA\">Pasta</option>\n<option value=\"BR\">Breakfast</option>\n<option value=\"MT\">Meat</option>\n<option value=\"SF\">Seafood</option>\n<option value=\"BP\">Bread and Pizza</option>\n<option value=\"DT\">Desserts</option>\n</select><input type=\"hidden\" name=\"reset_recipe\" id=\"id_reset_recipe\" /></td></tr>\n\t</table>\n\t<p><input type=\"submit\" value=\"Submit\"></p>\n</form>\n</body>"}

这是我的ajax代码:

<script type="text/javascript"> 
$(document).ready(function(){
    var form = $('form#createrecipeform');
    form.submit(function(e) {
    e.preventDefault();
    console.log('ajax form submission function called successfully.');
    //form = $(this);
    console.log(form)
    var serialized_form = form.serialize();
        $.ajax({ type: "POST", 
            url: $(this).attr('action'),
            data: serialized_form, 
            success: (function(data) { 
                console.log('ajax success function called successfully.');
                data = $.parseJSON(data);
                if (data.success) {
                    console.log('success');
                } else {        
                    console.log('failure');
                    var newForm = data.form;
                    form.replaceWith(newForm);  
                }
            })
        });
        return false;
    });
});
</script> 

这里是视图:( createrecipe是表单的动作,帐号是加载ajax的页面)

def createrecipe(request):
        print "entering createrecipeview"
        if request.method == 'POST':
            print "form is a post"
            form = RecipeForm(request.POST)
            print form.errors
            if form.is_valid():
                print "form is valid"
                form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})
                form = form.save()

                t = loader.get_template('cookbook/create_form.html')
                c = RequestContext(request, {
                'form': form,
                })

                data = {
                'replace': True,
                'form': t.render(c),
                'success': True,
                }

                json = simplejson.dumps(data)
                return HttpResponse(json, mimetype='text/plain')
            else:
                print "form is invalid"
                form = RecipeForm(request.POST)
                t = loader.get_template('cookbook/create_form.html')
                c = RequestContext(request, {
                    'form':form,
                })

                data ={
                    'form': t.render(c),
                    'success': False,
                }

                json = simplejson.dumps(data)
                return HttpResponse(json, mimetype='text/plain')

def account(request):
    user = request.user
    if request.user.is_authenticated():

        cookbooks = user.cookbooks
        if cookbooks.all().exists():
            cookbook = cookbooks.all()[0]
            form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})
            recipe_list = cookbook.recipes.all()
        else:
            raise Http404
    else:
        return HttpResponseRedirect('/accounts/login')
    t = loader.get_template('cookbook/account.html')
    c = RequestContext(request, {
        'form': form,
        'recipe_list': recipe_list
    })
    return HttpResponse(t.render(c))

这是create_form.html模板:

<head>

</head>
<body>
<form action="{% url cookbook.views.createrecipe %}" method="POST" name="recipeform" id="createrecipeform">
    <table>
        {% csrf_token %}
        {{ form.as_table }}
    </table>
    <p><input type="submit" value="Submit"></p>
</form>
</body>

以下是包含create_form模板的帐户模板:

{% extends "cookbook/base.html" %}
{% load pagination_tags %}
{% load comments %}


    <h1>{{ user }}'s Cookbook</h1>

<ul>
{% block nav-cookbooks %}
<li><a class="nav-inactive" href="/cookbooks/">Cookbooks</a></li>
{% endblock %}
{% block nav-account %}
<li><a class="nav-active" href="/account/">My Cookbook</a></li>
{% endblock %}
</ul>
{% block content %}
{% autopaginate recipe_list 6 %}
    <div id="recipe_cont">
            {% for recipe in recipe_list %}
        <div class="recipe">
            <div class="button">    
            <a href="{% url cookbook.views.userrecipe recipe.id %}" style="display: none;"></a>   
            <img src="{{ STATIC_URL }}chicknbraw.jpg" alt="" height="70" width="70" style="display:inline;" />
            <h4>{{ recipe.name }}</h4>
             </div>
            <h5>{{ recipe.author }}</h5>
            <h5>Prep Time: {{ recipe.prep_time }} minutes</h5>

            <h6><a href="/addrecipe/{{ recipe.id }}">Add Recipe</a>
                <a href="/removerecipe/{{ recipe.id }}">Remove Recipe</a></h6>
        </div>
    {% endfor %}
    </div>

    <div id="popupContact" class="popup">
            <a id="popupContactClose" style="cursor:pointer;float:right;">x</a>
            <p id="contactArea">
            <h1 style="text-align:center">Create New Recipe</h1>
            {% include 'cookbook/create_form.html' %} 
            </p>
    </div>
    <div id="backgroundPopup">
    </div>  
    <div id="col2-footer">
    {% paginate %}
    <p id="recipe_order_text"> order by: <a href="/userbook/ordered/name">abc</a>|<a href="/userbook/ordered/date">date</a> 
    </div>

{% endblock %}

{% block footer %}
        <a class="create" style="cursor:pointer" >Create New Recipe</a>
{% endblock %}

很抱歉放了这么多代码,但它似乎都依赖于另一段代码,所以我认为所有相关的代码都会有所帮助

感谢你能给我的任何帮助

凯蒂

1 个答案:

答案 0 :(得分:0)

在你的javascript中,你正在劫持表单,以便通过ajax提交,但之后你在表单上调用replaceWith,这样你的被劫持表单就会被删除,并被一个新的,未被劫持的表单所取代。要解决这个问题,你可以

1)只替换表单的内容 - 这应该有效,因为你只是将事件附加到表单本身而不是它的子元素

2)将您的js写成一个函数,您可以先在初始表单上调用,然后在通过ajax加载的任何新表单上调用。

更新:例如,

<script type="text/javascript"> 
$(document).ready(function(){

    function hijack() {
        var form = $('form#createrecipeform');
        form.submit(function(e) {
            e.preventDefault();
            console.log('ajax form submission function called successfully.');
            //form = $(this);
            console.log(form)
            var serialized_form = form.serialize();
            $.ajax({ type: "POST", 
                url: $(this).attr('action'),
                data: serialized_form, 
                success: (function(data) { 
                    console.log('ajax success function called successfully.');
                    data = $.parseJSON(data);
                    if (data.success) {
                        console.log('success');
                    } else {        
                        console.log('failure');
                        var newForm = data.form;
                        form.replaceWith(newForm);
                        hijack();
                    }
                })
            });
            return false;
        });
    };

    hijack();

});
</script>