簡體   English   中英

過濾inlineformset_factory的字段

[英]filtering fields of an inlineformset_factory

我有這些模型:

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)

這個內聯形式:

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)

但現在它顯示沒有字段,我該如何處理?

提前致謝

在您的視圖中嘗試此操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM