我正在使用我的 3 层模型实现嵌套内联,并且目前正在使用它。但是,即使我传递了正确的实例,我也无法限制我relevantindicator
的下拉选项。当前relevantindicator
在下拉选择中显示表中的所有值。我想将值限制为仅与disease
实例关联的值。有没有办法做到这一点?
我正在使用正确的方法在 Django和http://yergler.net/blog/2009/09/27/nested-formsets-with-django/中保存嵌套表单集作为参考。
模型.py
class Disease(models.Model):
disease = models.CharField(max_length=255)
class Indicator(models.Model):
relevantdisease = models.ForeignKey(Disease)
indicator = models.CharField(max_length=255)
class IndicatorValue(models.Model):
relevantindicator = models.ForeignKey(Indicator)
indicator_value = models.CharField(max_length=50)
表格.py
class BaseIndicatorFormSet(BaseInlineFormSet):
def __init__(self, *args, **kwargs):
try:
instance = kwargs.pop('instance')
except KeyError:
super(BaseIndicatorFormSet, self).__init__(*args, **kwargs)
def save_new(self, form, commit=True):
instance = super(BaseIndicatorFormSet, self).save_new(form, commit=commit)
form.instance = instance
for nested in form.nested:
nested.instance = instance
for cd in nested.cleaned_data:
cd[nested.fk.name]=instance
return instance
...
def add_fields(self,form,index):
super(BaseIndicatorFormSet, self).add_fields(form, index)
try:
instance = self.get_queryset()[index]
pk_value = instance.pk
except IndexError:
instance=None
pk_value = hash(form.prefix)
form.nested = [
IndicatorValueFormSet(
disease = instance,
queryset = IndicatorValue.objects.filter(relevantindicator = pk_value),
prefix = 'value_%s' % pk_value)]
class BaseIndicatorValueFormSet(BaseModelFormSet):
def __init__(self, disease, *args, **kwargs):
super(BaseIndicatorValueFormSet, self).__init__(*args, **kwargs)
self.disease = disease
def save_new(self, form, commit=True):
instance = form.save(commit=False)
instance.disease = self.disease
if commit:
instance.save()
return instance
def save_existing(self, form, instance, commit=True):
return self.save_new(form, commit)
class IndicatorValueForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
try:
disease_obj = kwargs.pop('disease')
except KeyError:
super(IndicatorValueForm, self).__init__(*args, **kwargs)
return
super(IndicatorValueForm, self).__init__(*args, **kwargs)
queryset = Indicator.objects.filter(relevantdisease =disease_obj)
self.fields['relevantindicator'].queryset = queryset
disease_obj = get_object_or_404(Disease, pk=2) #hard-wired
CurriedForm = formset_factory(IndicatorValueForm, extra=3)
CurriedForm.form = staticmethod(curry(IndicatorValueForm, disease = disease_obj))
IndicatorValueFormSet = inlineformset_factory(Indicator, IndicatorValue, formset=BaseIndicatorValueFormSet, form = CurriedForm, extra=3)
IndicatorFormSet = inlineformset_factory(Disease, Indicator, formset=BaseIndicatorFormSet, extra=0)
视图.py
disease = get_object_or_404(Disease, pk=disease_id)
if request.method == "POST":
formset = IndicatorFormSet(request.POST, instance=disease)
if formset.is_valid():
rooms = formset.save_all()
return HttpResponseRedirect(reverse('option', kwargs={'disease_id':disease_id}))
else:
formset = IndicatorFormSet(instance=disease)
context = {'disease': disease, 'indicators': formset, 'hide_breadcrumb':hide_breadcrumb}
return render_to_response('valdrui.html',context, context_instance=RequestContext(request))
模板.html
{% if relevantindicator.nested %}
{% for formset in relevantindicator.nested %}
{{ formset.as_table }}
{% endfor %}
{% endif %}
更新 我的感觉是我需要将疾病实例从 form.nested 传递到 BaseIndicatorValueFormSet。但它似乎不起作用。
提供清晰的屏幕截图。
relatedindicator 提供了一个下拉菜单
当有indicator_value 时,选择正确的相关指标。但是,当添加新的indicator_value 时,所有相关疾病的所有相关指标都可用。我想将相关指标选择限制为相关疾病(疾病实例)
更新 2:我必须instance
在 BaseIndicatorFormSet 下定义一个def __init__
. 我还需要在 forms.py 中定义表单,因为BaseIndicatorFormSet
调用IndicatorValueFormSet
。该实例当前是硬连线的,只是为了查看模板是否会呈现。不幸的是,模板中的表单不会呈现,但也不会产生任何错误。我不知道为什么,因为没有产生错误。