我有两个由 ForiegnKey 链接的模型,我想使用 django-crispy-forms 将 PhoneNumber 模型中的字段用于我的表单。
我尝试过的是使用语法“phone_number__number”,但这只会在表单中给我一个空的下拉列表。
这是我的模型,除了 phone_number 之外的所有内容都从这篇文章的 Customer 模型中取出:
class Customer(models.Model):
phone_number = models.ForeignKey(PhoneNumber)
class PhoneNumber(models.Model):
TYPES = (
('Cell', 'Cell'),
('Home', 'Home'),
('Fax', 'Fax'),
('Work', 'Work'),
)
primary = models.BooleanField(default=False)
phone_type = models.CharField(max_length=30, choices=TYPES, default='Cell')
number = models.CharField(max_length=15)
而我的表格,只有 phone_number 字段:
class CustomerCreateForm(forms.ModelForm):
'''
Base form for creating customers
'''
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
'Personal Information',
'phone_number__number',
),
FormActions(
Submit('submit' , 'Submit' , css_class='btn btn-success'),
Button('cancel' , 'Cancel' , css_class='btn btn-warning', onclick='javascript:history.go(-1);'),
)
)
super(CustomerCreateForm, self).__init__(*args, **kwargs)
class Meta:
model = Customer
exclude = (
'create_user',
'modify_user'
)