在 Django ModelForm 中添加和初始化自定义字段
Add and initialize custom field in 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'})
这是推荐的方法。根本不必重写 init 方法。
我觉得我遗漏了一些非常基本的点,但无法解决这个问题。
假设我有这样的模型:
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'})
这是推荐的方法。根本不必重写 init 方法。