如何消除ManytoMany表单字段中的选择

时间:2018-01-30 16:42:29

标签: python django

我有这个型号:

class Transaction(models.Model):
    date = models.DateTimeField(auto_now_add=True)
    buyer = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="buyer")
    smokers = models.ManyToManyField(UserProfile)
    price = models.FloatField(blank=True)

并有这样的形式:

class TransactionForm(ModelForm):
    class Meta:
        model = Transaction
        fields = ['smokers', 'price',]

我想访问吸烟者字段并消除一些选项(用户无法选择它或甚至在HTML中看到它)。这甚至可能吗?

1 个答案:

答案 0 :(得分:1)

您可以使用以下格式__init__()方法执行此操作:

class TransactionForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['smokers'].queryset = UserProfile.objects.filter(...)  # your filter

    class Meta:
        model = Transaction
        fields = ('smokers', 'price',)