我创建了一个 ModelChoiceForm,它动态填充了所有不具有 FlatPageExtras.child_of 值的平面页面。为此,我进行了以下设置:
表格.py:
class FlatPageExtrasForm(ModelForm):
class Meta:
model = FlatPageExtras
fields = ['head_content', 'endbody_content', 'new_page', 'child_of']
def __init__(self, *args, **kwargs):
super(FlatPageExtrasForm, self).__init__(*args, **kwargs)
self.fields['child_of'] = forms.ModelChoiceField(queryset = FlatPage.objects.filter(sites = Site.objects.get_current()).exclude(flatpageextras__child_of__isnull=False),widget = forms.Select, required = False)
视图.py:
def edit(request, flatpage_id):
site = Site.objects.get_current()
...
if request.method == "POST":
if request.POST.has_key("update"):
return update(request, page)
...
else:
flatpageextras_obj, result = FlatPageExtras.objects.get_or_create(flatpage=page)
form = FlatPageForm(instance=page)
form_flatpageextras = FlatPageExtrasForm(instance=flatpageextras_obj)
模板:
{{ form_flatpageextras.child_of }}<label for="id_child_of">Page on your site you would like this to appear under. </label></p>
{% if form_flatpageextras.child_of.errors %}
{{ form_flatpageextras.child_of.errors }}
{% endif %}
<p class="help-text">If a page is selected, that will be the parent site for this one. Leave blank if you would like no associations</p>
</div>
这一切都有效......几乎!当我转到提供的模板时,下拉菜单就在那里,正确显示了可用的平面页面,但它最初总是显示为空白,即使该字段已正确保存到所选页面的任何位置。如何让下拉菜单正确显示当前选择?