过滤inlineformset_factory的字段

时间:2011-12-26 15:16:25

标签: python django

我有这些模特:

class TourItem(models.Model):
   Tour=models.ForeignKey(Tour)
   TourItemType=models.ForeignKey(TourItemType)
   Transfer=models.ForeignKey(Transfer)
   Accommodate=models.ForeignKey(Accommodate)
   Visit=models.ForeignKey(Visit)

class Tour(models.Model):
   Lang_Choices=(
      ('fa',ugettext_lazy('Persian')),
      ('en',ugettext_lazy('English')),
      ('fr',ugettext_lazy('French')),
   )
   Lang=models.CharField(max_length=1,choices=Lang_Choices,editable=False)
   Name=models.CharField(max_length=100)
   Description=models.TextField()
   ActionDate=models.DateTimeField(auto_now=True,editable=False)

和这个inlineformset:

TourItemFormSet=inlineformset_factory(Tour,TourItem,can_delete=True,extra=4)

容纳,TourItemType,转移和访问模型有一个名为Lang的字段,当我制作formset时,我在每种形式中为这些模型设置了4个组合框,现在我想用request.LANGUAGE_CODE过滤这些组合框。我搜索了很多结束了这段代码:

def get_field_qs(field, **kwargs):
      if field.name == 'TourItemType':
     field.queryset = TourItemType.objects.filter(Lang__iexact=request.LANGUAGE_CODE)
      return field
   TourItemFormSet=inlineformset_factory(Tour,TourItem,formfield_callback=get_field_qs,can_delete=True,extra=4)

但现在它显示没有字段,我该如何处理?

提前致谢

1 个答案:

答案 0 :(得分:2)

视图

中尝试此操作
TourItemFormSet = inlineformset_factory(Tour,TourItem,can_delete=True,extra=4)
TourItemFormSet.form.base_fields["TourItemType"].queryset = TourItemType.objects.filter(Lang__iexact=request.LANGUAGE_CODE)
# then create an instance of TourItemFormSet and add to template context