inlineformset工厂的筛选字段

2024-06-28 19:00:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这些模型:

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)

Accountable、TourItemType、Transfer和Visit Models有一个名为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)

但现在它没有显示字段,我怎么处理这个?你知道吗

提前谢谢


Tags: 模型truefieldlangmodelsvisitlazyclass
1条回答
网友
1楼 · 发布于 2024-06-28 19:00:17

视图中尝试以下操作:

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

相关问题 更多 >