如何使用模型数据初始化表单的Image和Integer字段?

时间:2019-06-25 04:30:11

标签: django

我设法初始化了CharField,但是如何对ImageField和IntegerField进行相同的处理呢? 我的forms.py:

class GoodGet(forms.ModelForm):
    class Meta:
        model = Good_Get
        Size = forms.ModelChoiceField(queryset = Good.objects.all())
        fields = '__all__'

    def __init__(self, *args, good_id1=None, **kwargs):
        super(forms.ModelForm, self).__init__(*args, **kwargs)
        if good_id1 is not None:
            obj = Good.objects.filter(id = good_id1)
            self.fields['Name'].initial = Good.objects.get(id=good_id1)
            self.fields['Photo'].initial = Good.objects.get(id=good_id1)
            self.fields['Price'].initial = Good.objects.get(id=good_id1)
            for good in obj:
                good_sizes = good.Size.all()
            self.fields['Size'].queryset = good_sizes

因此,我需要正确编写以下字符串:

            self.fields['Photo'].initial = Good.objects.get(id=good_id1)
            self.fields['Price'].initial = Good.objects.get(id=good_id1)

如何? 好的模型:

class Good(models.Model):
    Name = models.CharField(max_length = 150)
    Type = models.ForeignKey('Type', on_delete=models.CASCADE, null=True)
    Available = models.CharField(max_length = 50)
    Photo = models.ImageField(upload_to = 'clothes_photos')
    Price = models.IntegerField(default = '0')
    Discount = models.IntegerField(default = '0')
    Size = models.ManyToManyField('Size')

1 个答案:

答案 0 :(得分:0)

最好在视图中初始化它。

good = Good.objects.filter(id = good_id1)
form = GoodGet(instance=good)