1

我想last_item在 django 表单提交后在 Twitter-Bootstrap 模态中显示,但是我不知道如何处理模态。我尝试了文档中建议的表单按钮,但它不处理表单数据。我需要做什么?

<button data-toggle="modal" data-target="#myModal2">Submit</button>

视图.py

def main(request):
    if request.method == 'POST':
        form = MyModelForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            request.session['name'] = name
            mm = MyModel.objects.create(name=name)
            mm.save()
            return HttpResponseRedirect('/') # Redirect after POST
    else:
        form = MyModelForm()
    args = {}
    args['last_item'] = MyModel.objects.all().order_by('pk').reverse()[0]
    args['form'] = form
    return render(request, 'form.html', args)

表单.html

{% extends "base.html" %}
{% block content %}

<form method="POST" id="" action="">
  {% csrf_token %}
  {{ form.as_p }}
  <button>Submit</button>
</form>

<div class="modal" id="myModal2" tabindex="-1" role="dialog"
     aria-labelledby="myModal2Label" aria-hidden="true" style="display: none">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModal2Label">Modal header</h3>
  </div>
  <div class="modal-body">
    <p>Last item: {{ last_item }}</p>
  </div>
</div>
{% endblock %}

{% block scripts %}
{% endblock %}
4

1 回答 1

1

It seems like bootstrap calls event.preventDefault() on click, which prevents the form from being submited.

You should bind your own event on this button and close the modal programaticaly.

It could look like:

$('form').submit(function() {
    $('#myModal2').modal('hide');
})

I did not test this code but it should be a good start.

于 2012-09-29T10:03:06.183 回答