django use model choices in modelform

Hans de Jong picture Hans de Jong · Dec 19, 2013 · Viewed 10.6k times · Source

I was wondering how i should use my model choices options, in my ModelForm.

Example(model):

class NPCGuild(models.Model):
    CATEGORIES=(
        ('COM', 'Combat'),
        ('CRA', 'Crafting'),
        ('WAR', 'Warfare'),
    )
    faction = models.ForeignKey(Faction)
    category = models.CharField(max_length=3, choices=CATEGORIES)
    name = models.CharField(max_length=63)

My Form:

class NPCGuildForm(forms.ModelForm):
    name = forms.CharField()
    category = forms.CharField(
                        some widget?)
    faction_set = Faction.objects.all()
    faction = forms.ModelChoiceField(queryset=faction_set, empty_label="Faction", required=True)

    class Meta:
        model = NPCGuild
        fields = ['name', 'category', 'faction']

As you can see, im not sure what i should be doing to get my choices from my model as a choicefield. Maybe it can be done with a ModelChoiceField as well, but then how to get the choices in it?

Can someone please help me out here

Answer

niekas picture niekas · Dec 19, 2013

You should specify model in the Meta class and fields will be generated automatically:

class NPCGuildForm(forms.ModelForm):
    class Meta:
        model = NPCGuild

You can add extra form fields if you want to. Read more about ModelFroms.

Update As karthikr mentioned in the comment. If you want to set available choices in a form field, you have to use forms.ChoiceField, like this:

category = forms.ChoiceField(choices=NPCGuild.CATEGORIES)