我已经围绕我在评论中链接到的博客文章建立了一个答案。
我首先找到了一种合乎逻辑的方法来在我的表单中包含“添加新”链接,我决定的解决方案是为我想要具有该功能的表单小部件提供模板。我的表格如下所示:
# core/forms.py
class IntranetForm(ModelForm):
def __init__(self, *args, **kwargs):
super(IntranetForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_class = 'form-horizontal'
# app/forms.py
class ComplaintForm(IntranetForm):
def __init__(self, *args, **kwargs):
super(ComplaintForm, self).__init__(*args, **kwargs)
self.helper.layout = Layout(
Field(
'case',
css_class='input-xlarge',
template='complaints/related_case.html',
),
Field('date_received', css_class = 'input-xlarge'),
Field('stage', css_class = 'input-xlarge'),
Field('tags', css_class = 'input-xlarge'),
Field('team', css_class = 'input-xlarge'),
Field('handler', css_class = 'input-xlarge'),
Field('status', css_class = 'input-xlarge'),
FormActions(
Submit(
'save_changes',
'Save changes',
css_class = "btn-primary"
),
Button(
'cancel',
'Cancel',
onclick = 'history.go(-1);'
),
),
)
class Meta:
model = Complaint
fields = (
'case',
'date_received',
'stage',
'tags',
'team',
'handler',
'status',
)
请注意在第一个字段中添加了一个模板参数。该模板如下所示:
<div id="div_id_case" class="control-group">
<label for="id_case" class="control-label ">Case</label>
<div class="controls">
<select class="input-xlarge select" id="id_case" name="case"></select>
<a href="{% url 'add_case' %}" id="add_id_case" class="add-another btn btn-success" onclick="return showAddAnotherPopup(this);">Add new</a>
</div>
</div>
当 django 渲染我的case_form.html
模板时,上面的 html 被插入为相关的表单字段。完整complaint_form.html
模板包含调用案例表单的 javascript 代码。该模板如下所示:
{% extends 'complaints/base_complaint.html' %}
{% load crispy_forms_tags %}
{% block extra_headers %}
{{ form.media }}
{% endblock %}
{% block title %}Register complaint{% endblock %}
{% block heading %}Register complaint{% endblock %}
{% block content %}
{% crispy form %}
<script>
$(document).ready(function() {
$( '.add-another' ).click(function(e) {
e.preventDefault( );
showAddAnotherPopup( $( this ) );
});
});
/* Credit: django.contrib.admin (BSD) */
function showAddAnotherPopup(triggeringLink) {
/*
Pause here with Firebug's script debugger.
*/
var name = triggeringLink.attr( 'id' ).replace(/^add_/, '');
name = id_to_windowname(name);
href = triggeringLink.attr( 'href' );
if (href.indexOf('?') == -1) {
href += '?popup=1';
} else {
href += '&popup=1';
}
href += '&winName=' + name;
var win = window.open(href, name, 'height=800,width=800,resizable=yes,scrollbars=yes');
win.focus();
return false;
}
function dismissAddAnotherPopup(win, newId, newRepr) {
// newId and newRepr are expected to have previously been escaped by
newId = html_unescape(newId);
newRepr = html_unescape(newRepr);
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem) {
if (elem.nodeName == 'SELECT') {
var o = new Option(newRepr, newId);
elem.options[elem.options.length] = o;
o.selected = true;
}
} else {
console.log("Could not get input id for win " + name);
}
win.close();
}
function html_unescape(text) {
// Unescape a string that was escaped using django.utils.html.escape.
text = text.replace(/</g, '');
text = text.replace(/"/g, '"');
text = text.replace(/'/g, "'");
text = text.replace(/&/g, '&');
return text;
}
// IE doesn't accept periods or dashes in the window name, but the element IDs
// we use to generate popup window names may contain them, therefore we map them
// to allowed characters in a reversible way so that we can locate the correct
// element when the popup window is dismissed.
function id_to_windowname(text) {
text = text.replace(/\./g, '__dot__');
text = text.replace(/\-/g, '__dash__');
text = text.replace(/\[/g, '__braceleft__');
text = text.replace(/\]/g, '__braceright__');
return text;
}
function windowname_to_id(text) {
return text;
}
</script>
{% endblock %}
那里的 javascript 完全是从我链接到的博客条目中复制/粘贴的,它CaseCreateView
在弹出窗口中调用 my ,其中包括我们已经查看过的表单。现在您需要该表单将返回值传递给您的原始页面。
我通过在案例详细信息页面中包含以下脚本来做到这一点。这意味着当我的表单重定向到保存时的详细信息页面时,我的表单将在调用脚本之前正确保存。详细模板如下所示:
{% extends 'complaints/base_complaint.html' %}
{% block content %}
<script>
$(document).ready(function() {
opener.dismissAddAnotherPopup( window, "{{ case.pk }}", "{{ case }}" );
});
</script>
{% endblock %}
这会在页面呈现后立即关闭。这对您来说可能并不理想,但您可以通过例如覆盖表单在保存时重定向到的页面并将其用作上述脚本的便利存储来更改该行为,但仅此而已。注意它是如何传回 case 主键和它的 unicode 表示的?这些现在将填充<option>
原始表单中的选定字段,您就完成了。