I'm trying to create a contact manager using Django. I've created a form with the following code:
class ContactForm(forms.ModelForm):
first_name = forms.CharField(max_length=20, help_text="First name")
last_name = forms.CharField(max_length=20, help_text="Last name")
email = forms.CharField(max_length=100, required=False, help_text="Email")
phone = forms.CharField(max_length=15, required=False, help_text="Phone")
company = forms.ChoiceField(widget=forms.Select, choices=Company.objects.all(), required=False, help_text="Company")
class Meta:
model = Contact
fields = ('first_name', 'last_name', 'email', 'phone', 'company')
I'm having problems with the company field. I don't know how to pass a list of all companies to the form so it can display as a select tag in html. I believe I have to convert it to a dictionary so the "choices" argument would work, but I'm not sure how to do it.
Using ModelChoiceField:
company = forms.ModelChoiceField(queryset=Company.objects.all(), required=False, help_text="Company")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With