在Django Modelform中添加和初始化自定义字段



我觉得我缺少一些非常基本的观点,但无法解决。
假设我有这样的模型:

class Person(models.Model):
    first_name = models.CharField(max_length=256, blank=True)
    # this is weird field, but needed for my usecase
    last_name = models.WeirdCustomField(max_length=256, blank=True)

,还有一个表格,我想自定义一些(注释):

class PersonForm(forms.ModelForm):
    class Meta:
        model = Address
        # I want to override 'last_name' field, so exclude it here
        exclude = ['last_name']
    # And add additional field
    my_field = ChoiceField(choices=list_of_choicec)
    last_name = forms.CharField()
    def __init__(self, *args, **kwargs):
        last_name = kwargs.pop('last_name', None)
        my_field = kwargs.pop('my_field', None)
        super(PersonForm, self).__init__(*args, **kwargs)
        self.fields['last_name'] = last_name
        self.fields['my_field'] = my_field

现在,在shell中(毕竟进口...)

person = Person.objects.get(first_name='Jacob')
person.first_name # Prints 'Jacob', correct!
form = PersonForm(instance=person, last_name='Smith', my_field='test123')
form['first_name'].value() # -> 'Jacob', that's right
form['last_name'].value() # -> nothing, I expected 'Smith'
form['my_field'].value() # -> nothing, I would like to see 'test123'

我认为我非常深入地挖掘互联网,但找不到解决此类问题的解决方案。

您必须设置初始值。在您的初始化中,尝试替换以下代码。

self.fields['last_name'].initial = last_name
self.fields['my_field'].initial = my_field

创建表单实例时也可以传递初始版本。

form = PersonForm(instance=person, initial={'last_name'='Smith', 'my_field'='test123'})

这是推荐的方法。完全不必覆盖初始方法。

最新更新