除非你需要使用模态之外的联系表格,否则这应该对你有用。如果确实需要在其他地方使用它,请维护两个版本(一个模式,一个不使用)。另外,一个技巧-给django-crispy-forms一个过渡-它可以帮助你使用twitter-bootstrap类呈现表单。
contact.html:
<div id="contactModal"><form method="post" action="/contact/edit/{{ item.id }}"> <div > <button type="button" data-dismiss="modal">×</button> <h3>Editing Contact</h3> </div> <div > {% csrf_token %} {{form.as_p}} </div> <div > <input type="submit" value="Save" /> <input name="cancel" type="submit" value="Cancel"/> </div></form></div>main_page.html
<html>...<a data-toggle="modal" href="#contactModal">Edit Contact</a>{% include "contact.html" %}...</html>编辑:
好的,现在我知道你可能有多个表单,将每个表单都隐藏在html中可能是个坏主意。你可能想要使用ajax-y版本,并按需加载每种表单。我在这里假设在表单提交时,整个页面都会重新加载。如果你要异步提交表单,请在其他地方找到答案。
我们将从重新定义
contact.html片段开始。它应该在模态中进行渲染,并包含与模态完美搭配所需的所有标记。
contact你最初拥有的视图很好-除非表单无效,
contact.html否则最终将呈现,而没有其他显示。
<form method="post" action="/contact/edit/{{ item.id }}"> <div > <button type="button" data-dismiss="modal">×</button> <h3>Editing Contact</h3> </div> <div > {% csrf_token %} {{form.as_p}} <!-- {{form|crispy}} if you use django-crispy-forms --> </div> <div > <input type="submit" value="Save" /> <input name="cancel" type="submit" value="Cancel"/> </div></form>现在,你的
main_page.html:
<html>.. snip ..<a href="#" data-form="/contact/edit/{{ item.id }}" title="Edit">edit</a><a href="#" data-form="/contact/edit/{{ item.id }}" title="Edit">edit</a><a href="#" data-form="/contact/edit/{{ item.id }}" title="Edit">edit</a><div id="contactModal"></div><script> $(".contact").click(function(ev) { // for each edit contact url ev.preventDefault(); // prevent navigation var url = $(this).data("form"); // get the contact form url $("#contactModal").load(url, function() { // load the url into the modal $(this).modal('show'); // display the modal on url load }); return false; // prevent the click propagation }); $('.contact-form').live('submit', function() { $.ajax({ type: $(this).attr('method'), url: this.action, data: $(this).serialize(), context: this, success: function(data, status) { $('#contactModal').html(data); } }); return false; });</script>.. snip ..</html>这都是未经测试的,但它应该为你提供一个良好的起点/起点。



