2

I have the following model:

from django.db import model

class Fruit(models.Model):
    fruit_name = models.CharField(max_length=100)

And A form like this:

from django import forms 
from .models import SomeModel

class FruitForm(forms.ModelForm):
    some_input = forms.CharField(max_length=100)
    class Meta:
        model = Fruit
        fields = ['fruit_name']

This guide shows me how to create a dropdown like this:

fruit = [
    ('orange', 'Oranges'),
    ('cantaloupe', 'Cantaloupes'),
    ('mango', 'Mangoes'),
    ('honeydew', 'Honeydews'),
]
class TestForm(forms.Form):
    some_input = forms.CharField(max_length=100)
    favorite_fruit = forms.CharField(widget=forms.Select(choices=FRUIT_CHOICES))

What I want to happen is for the key/value tuple list to generate based on the fruit_id and fruit_name columns of the Fruit model, without the need to manually insert the data into the FruitForm.

What am I missing here?

1 Answer 1

2

Usually you do that with a ModelChoiceField [Django-doc]:

from django import forms

class TestForm(forms.Form):
    some_input = forms.CharField(max_length=100)
    favorite_fruit = forms.ModelChoiceField(queryset=Fruit.objects.all())

In your Fruit model, you then implement the __str__ method to decide how to render your fruit. Here that would be:

from django.db import model

class Fruit(models.Model):
    fruit_name = models.CharField(max_length=100)

    def __str__(self):
        return self.fruit_name

You can alter the queryset= parameter, for example to filter the queryset in advance. For example if you only want to show Fruit that starts with an A, you can filter like:

from django import forms

# example: only show fruit that starts with an A
class TestForm(forms.Form):
    some_input = forms.CharField(max_length=100)
    favorite_fruit = forms.ModelChoiceField(
        queryset=Fruit.objects.filter(fruit_name__startswith='A')
    )
Sign up to request clarification or add additional context in comments.

Comments

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.