【发布时间】: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