【问题标题】:Add and initialize custom field in Django ModelForm在 Django ModelForm 中添加和初始化自定义字段
【发布时间】:2018-05-15 12:37: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)

还有一个表格,我想定制一下(cmets):

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'

我认为我在互联网上挖掘得很深,但找不到此类问题的解决方案。

【问题讨论】:

    标签: python django forms model django-1.11


    【解决方案1】:

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

    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 方法。

    【讨论】:

    • 太棒了,我不认为我会在不久的将来自己弄清楚,谢谢!我还需要说,这很反直觉,但我猜这是框架方式。
    • 尝试在你的初始化中打印 self.fields['my_field']。你可以看到它是什么。
    • 如何在通用视图中执行此操作??
    • 您使用的是哪种通用视图?
    猜你喜欢
    • 1970-01-01
    • 2013-02-21
    • 2019-10-04
    • 2020-08-09
    • 2013-07-23
    • 2012-01-26
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多