4

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.

2 Answers 2

6

Using ModelChoiceField:

company = forms.ModelChoiceField(queryset=Company.objects.all(), required=False, help_text="Company")
Sign up to request clarification or add additional context in comments.

2 Comments

This works too, but the solution provided by LuRsT gives you the option to use a PK so the form would pick the value of an instance if I were to use it as an editing form, which is what I really wanted. I believe I should have asked better. Thanks anyway!
Actually, after having some issues with the answer provided by LuRsT I tried again this one and it worked just fine!
0

You need to pass a tuple or list of 2-tuples to the choices kwarg.

https://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ChoiceField.choices

Try this:

company = forms.ChoiceField(widget=forms.Select, choices=Company.objects.all().values_list(pk, name), required=False, help_text="Company")

https://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list

3 Comments

@angardi you're welcome, can you mark my answer as the solution so that the question is closed? Thanks
I've had some problems with that code, At first it seemed to work because it gave me the list and selected the correct option from the drop-down, but when I tried to save the form I got an error saying that the company I've selected didn't exist. That doesn't happen with Omid Raha answer.
Ah of course, I overlooked that you were using a ModelForm, that's why Omid's answer works and not mine since the Form is excepting a model and not a pk.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.