点击按钮保存django表单

时间:2015-07-06 10:23:19

标签: javascript python html django

我目前正在尝试学习django。我决定创建一个小应用程序。目前我正在制作一个表单,在一个页面上创建VoteType和Voting候选人。我创建了一个页面,您可以根据需要添加任意数量的候选字段,但是当我单击按钮时没有任何事情发生,即使我没有单击按钮,也会保存一些数据。我正在youtube看这个django指南。这家伙正在制作一个简单的表格。他将method = POST和action =''添加到...并在他使用的视图中(request.POST或None)。我尝试做类似的,但由于我的形式有点复杂,我真的很困惑。

所以这是我的views.py代码:

def create(request):
    voteTypeForm = VoteTypeForm(request.POST or None)
    voteForm = VoteForm(request.POST or None)
    instance = voteTypeForm.save(commit=False)
    instance.pub_date = timezone.now()
    instance.save()
    instance2 = voteForm.save(commit=False)
    instance2.save()
    #print instance.pub_date
    context = RequestContext(request,{
            'voteTypeForm': voteTypeForm,
            'voteForm': voteForm,
    })
    return render(request, 'Vote/create.html', context)

这是我的create.html django模板:

{% load staticfiles %}
    <link rel="stylesheet" type="text/css" href="{% static 'Vote/style.css' %}" />
<fieldset id="fieldset">
    <form method = 'POST' action = ''>{%csrf_token %}
        <p>{{ voteTypeForm }}</p>
    </form>
        <div id="placeholder">

        </div>
        <p>
            <button type="button" name="Submit" onclick="Add();">+</button>
        </p>
    <input type = 'submit' value="create"/>
</fieldset>
<script type='text/javascript'>
{#    document.write(code);#}
    var _counter = 0;
    var template = document.createTextNode('')
    function appendStringAsNodes(element, html) {
        var frag = document.createDocumentFragment(),
            tmp = document.createElement('body'), child;
        tmp.innerHTML = html;
        // Append elements in a loop to a DocumentFragment, so that the browser does
        // not re-render the document for each node
        while (child = tmp.firstChild) {
            frag.appendChild(child);
        }
        element.appendChild(frag); // Now, append all elements at once
        frag = tmp = null;
    }
    function Add() {
        var code = '<div id="template">' +
                '<p>' +
                    '<fieldset id="fieldsets">' +
                        '<legend id="legends">Candidate No ['+ String(_counter+1) +']</legend>' +
                       ' <form method = "POST" action = "">'+
                              '<input type="hidden" name="csrfmiddlewaretoken" value="{{csrf_token }}" />' +
                            '<p><label for="id_name">Name:</label> <input id="id_name" maxlength="50" name="name" type="text" /></p>'+
                            '<p><label for="id_image">Image:</label> <input id="id_image" name="image" type="file" /></p>'+
                        '</form>' +
                   ' </fieldset>' +
                '</p>' +
            '</div>';
        _counter++;
        appendStringAsNodes(document.getElementById("placeholder"),code);
        document.getElementById("someInput").value = _counter;
    }
</script>

如何修复此代码,以便我的程序仅在按下创建按钮时保存实例?

2 个答案:

答案 0 :(得分:1)

您仍然需要检查操作是否为POST,并且表单是否有效,并且您必须在成功提交后重定向。

def create(request):
    voteTypeForm = VoteTypeForm(request.POST or None)
    voteForm = VoteForm(request.POST or None)
    if request.method == 'POST':
        # check validity separately to avoid short-cutting
        vote_type_valid = voteTypeForm.is_valid()
        vote_form_valid = voteForm.is_valid()
        if vote_type_valid and vote_form_valid:
            instance = voteTypeForm.save(commit=False)
            instance.pub_date = timezone.now()
            instance.save()
            instance2 = voteForm.save(commit=False)
            instance2.save()
            return redirect('<view-you-redirect-to-on-success'>
    context = RequestContext(request,{
            'voteTypeForm': voteTypeForm,
            'voteForm': voteForm,
    })
    return render(request, 'Vote/create.html', context)

答案 1 :(得分:-1)

最简单的方法是在按下提交按钮时发出ajax请求。 考虑到您有一个表单&#39; voteForm&#39;,请尝试使用django的内置模板加载此表单,如下所示:

{{voteForm.as_p}}

这将创建您已经完成的表单。
现在,当您按下提交按钮时,请在其中发出包含您的表单数据的ajax请求。

ajax请求会将您的数据带到表单并返回一个响应,您可以使用该响应进一步执行处理。 ajax请求的一个简单示例是:

    function youfunctionname()
        $.ajax({
                   type: "POST",
                   url: url,
                   data: $("#yourformname").serialize(), // serializes the form's elements.
                   success: function(data)
                   {
                       alert(data);
                   }
                 });
  }