在Django ModelForm中添加并初始化自定义字段

时间:2017-12-01 11:53:37

标签: python django forms model django-1.11

我觉得我错过了一些非常基本的观点,但无法解决这个问题 假设我有这样的模型:

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'

我认为我深入挖掘互联网,但无法找到解决此类问题的方法。

1 个答案:

答案 0 :(得分:2)

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

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'})

这是推荐的方法。根本不必覆盖init方法。

相关问题