1

我正在开发一个 django 项目,其中一个模板在弹出 div 中有一个表单,该表单提交一个表单以创建一个新对象。

到目前为止,ajax 函数已成功提交表单并将配方添加到管理数据库,但由于某种原因,它没有出现在我传递到模板中的 object_list 中。

即使我刷新页面,新添加的对象也不会添加到模板中,并且创建的对象会卡在管理页面上的边缘。

代码

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');
                        alert('recipe added');
                    } else {        
                        console.log('failure');
                        var newForm = data.form;
                        form.replaceWith(newForm);
                        hijack();
                    }
                })
            });
            return false;
        });
    };
    hijack();
});
</script> 

相关观点:

   ** //this is the page the has the popup div to load the form**
    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))


    **//this is the page that handles the ajax and is the action of the form**
    def createrecipe(request):
            if request.method == 'POST':
                form = RecipeForm(request.POST)     
                if form.is_valid():
                    form = form.save(commit=False)
                    form.original_cookbook = request.user.cookbooks.all()[0]
                    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:
                    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')

模板:

    {% block content %}
        <div id="recipe_cont">
                {% for recipe in recipe_list %}// here is where add each recipe in the recipe list
            <div class="recipe">
                <div id="recipebutton{{ forloop.counter }}" class="button"> 
                </div>
            </div>
        {% endfor %}
        </div>

            <div id="popupContact" class="popup">
                <a id="popupContactClose" style="cursor:pointer;float:right;">x</a>
                <p id="contactArea">
                    <div id="create_form_span">
                        {% include 'cookbook/create_form.html' %} // here is the form 
                    </div>
                </p>
            </div>
        </div>

    {% endblock %}


//template for the form that is included
    <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>
4

0 回答 0