from yourapp.models import PhoneNumber
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',
),
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)
self.fields["phone_number"].choices = \
[(item.number, item.number) for item in PhoneNumber.objects.all()]
class Meta:
model = Customer
exclude = (
'create_user',
'modify_user'
)
How to use field in a linked table as a field in django-crispy-forms?
-
30-11-2021 - |
Question
I have two models that are linked by ForiegnKey, and I'd like to use the fields in the PhoneNumber model for my form, using django-crispy-forms.
What I've tried is using the syntax 'phone_number__number', but that only gives me an empty drop down list in the form.
Here are my models, with everything but phone_number taken out of the Customer model for this post:
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)
And my form, with only the phone_number field:
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'
)
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow