如何用模型值填充表单字段

时间:2019-06-24 18:06:56

标签: django

我正在尝试用模型Good的数据填写表单。我使用id过滤以获取某些对象。我需要重写init函数来设置一个有效的查询集,并且它可以工作。现在,我需要为其他字段填充值。

这是我的表格。py:

class GoodGet(forms.ModelForm):
    class Meta:
        model = Good_Get
        Size = forms.ModelChoiceField(queryset = Good.objects.all())
        Name = forms.CharField(widget = forms.TextInput(attrs = {'value': 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)
            for good in obj:
                good_sizes = good.Size.all()
            self.fields['Size'].queryset = good_sizes

我需要做这样的事情:

    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.Name = obj.Name    <---
            for good in obj:
                good_sizes = good.Size.all()
            self.fields['Size'].queryset = good_sizes

那么,如何用Good模型的数据填充其他字段的值?

2 个答案:

答案 0 :(得分:0)

您可以将初始值设置为:

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

因此,我们使用Good.objects.get(..)来检索与给定id匹配的Good对象,并将该对象的Name属性作为该字段的.initial值传递。

但是,如果仅用对象的值初始化ModelForm,则可以使用instance= parameter [Django-doc],例如:

# construct a form with data from an instance
GoodGet(instance=Good.objects.get(id=some_id))

话虽这么说,您的GoodGet表格中有一些奇怪的部分。最好添加一个Form后缀,在类中而不是Meta类中指定字段,并且使用{ 'value': Good.object.all() }没有意义,因为该值不能是一个集合Good个对象中。

class GoodGetForm(forms.ModelForm):
    Size = forms.ModelChoiceField(queryset=Good.objects.all())
    Name = forms.CharField(widget=forms.TextInput()}))
    class Meta:
        model = Good_Get
        fields = '__all__'

    # ...

答案 1 :(得分:0)

1048
1032
1024
32
32
0x7ffcdec7ea90  // Ench
0x7ffcdec7ea98  // Durability - 8 bytes later so Ench takes 8 bytes
0x7ffcdec7eaa0  // Name - 8 bytes later so Durability takes 8 bytes
0x7ffcdec7eaa8  // ID - 8 bytes later so Name takes 8 bytes
0x7ffcdec7eab0  // Ench of next element - 8 bytes later so ID takes 8 bytes

我的情况一定是这样