Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get List of objects in django form

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.

like image 577
angardi Avatar asked Oct 26 '25 21:10

angardi


1 Answers

Using ModelChoiceField:

company = forms.ModelChoiceField(queryset=Company.objects.all(), required=False, help_text="Company")
like image 51
Omid Raha Avatar answered Oct 28 '25 10:10

Omid Raha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!