Tristan Tran
Tristan Tran

Reputation: 1533

Use an app's model's object fields as form ChoiceField in another app

I have two apps,menu and table

This is a model in app menu

class Item(models.Model):
    name = models.CharField(verbose_name="Item Name", max_length=200, db_index=True)

And in app table, I have a form.py as following:

from django import forms

class TableForm(forms.Form):
    item = forms.ChoiceField(choices= xxx)

I would like to use the list of all object names in the model Item as a choicelist in the form. The objects of Item could be created both by admin and elsewhere in my project during runtime and updated in the database. Could someone advise? Thanks.

Upvotes: 1

Views: 88

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477437

It is better to use a ModelChoiceField [Django-doc]. If you override the __str__(…) method, the method that tells how the textual representation of an object looks like, we can work with a

class Item(models.Model):
    name = models.CharField(
        verbose_name='Item Name',
        max_length=200,
        db_index=True
    )

    def __str__(self):
        return self.name

Then the form looks like:

from django import forms
from menu.models import Item

class TableForm(forms.Form):
    item = forms.ModelChoiceField(queryset=Item.objects.all())

It might be a good idea to make the name of an Item unique, such that no two Items are given the same name, this could result in confusion, since if two items are named Apple, then the question is "What is the right apple?":

class Item(models.Model):
    name = models.CharField(
        verbose_name='Item Name',
        max_length=200,
        db_index=True,
        unique=True  # ← mark the name as unique
    )

    # …

Upvotes: 1

Related Questions