默认情况下,CreateView / UpdateView只包含一个下拉列表,用于选择已存在的ForeignKey相关对象。
使用django-crispy-forms,我如何拥有CreateView或UpdateView,它不仅包括我的模型的字段,还包括用于创建通过ForeignKey相关的新模型的字段?
使用CreateView / UpdateView和使用常规FBV会更好吗?如果是这样,我该怎么做呢?
我在学习Django的过程中没有太多问题,但是围绕视图/表单/模型的交互方式进行思考并不容易。
class Property(models.Model):
name = models.CharField(max_length=128)
address = models.ForeignKey(PostalAddress, blank=True, null=True)
class PostalAddress(models.Model):
street_address = models.CharField(max_length=500)
city = models.CharField(max_length=500)
state = USStateField()
zip_code = models.CharField(max_length=10)
class PropertyUpdateView(UpdateView):
model = Property
class PropertyCreateView(CreateView):
model = Property
我一直在尝试将form_class = PropertyForm
添加到CreateView / UpdateView,并使用以下内容:
class PropertyForm(ModelForm):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_id = 'id-propertyForm'
self.helper.form_method = 'post'
self.helper.layout = Layout(
Fieldset(
'Edit Property',
'name',
),
ButtonHolder(
Submit('submit', 'Submit')
)
)
super(PropertyForm, self).__init__(*args, **kwargs)
class Meta:
model = Property
......但我不知道从哪里开始。
答案 0 :(得分:1)
我已在我评论中链接的blog post附近建立了答案。
我首先找到了一种逻辑方式,在我的表单中包含“添加新”链接,我解决的解决方案是为我希望拥有该功能的表单小部件提供模板。我的表格如下:
# 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
,其中包括我们已经查看过的表单。现在,您需要该表单将返回值传递给原始页面。
我通过在详细信息页面中包含以下脚本来完成此操作。这意味着我的表单在调用脚本时会在保存时重定向到详细信息页面时正确保存。详细信息模板如下所示:
{% extends 'complaints/base_complaint.html' %}
{% block content %}
<script>
$(document).ready(function() {
opener.dismissAddAnotherPopup( window, "{{ case.pk }}", "{{ case }}" );
});
</script>
{% endblock %}
这会在呈现页面后立即关闭页面。这对你来说可能并不理想,但你可以改变这种行为,例如,覆盖你的表单在保存时重定向到的页面,并将其用作上述脚本的方便存储,但没有别的。请注意它是如何传回case主键并且它是unicode表示的?现在,这些将填充原始表单中的选定<option>
字段,您已完成。