django为许多领域创建模型

时间:2014-12-09 20:29:17

标签: python django django-models django-forms

我正在制作食谱网站,因此我有食谱模型,我想要创建这样的形式:

class Recipe(models.Model):
    ....
    products = models.ManyToManyField(ProductMeasurement)
    ....

我已经有ProductMeasurement模型和表格了:

class ProductMeasurement(models.Model):
    product = models.ForeignKey(Product)
    measurement = models.ForeignKey(Measurement)
    value = models.FloatField()

 class FridgeForm(forms.Form):
    product = forms.ModelChoiceField(queryset=None, widget=forms.Select(attrs={'class': 'form-control'}))
    amount = forms.DecimalField(decimal_places=2, widget=forms.NumberInput(attrs={'class': 'form-control'}))
    measurement = forms.ModelChoiceField(queryset=None, widget=forms.Select(attrs={'class': 'form-control'}))

    def __init__(self, *args, **kwargs):
        super(FridgeForm, self).__init__(*args, **kwargs)
        self.fields['product'].queryset = Product.objects.all()
        self.fields['measurement'].queryset = Measurement.objects.all()

我想要做的是为食谱模型创建表单。问题是用户想要的配方不会有ProductMeasurements。因此,我需要找到一种方法,以便用户可以在Recipe表单中创建ProductMeasurement。这里有什么可行的方法?

1 个答案:

答案 0 :(得分:0)

django formsets是我一直在寻找的。