django use model choices in modelform


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


class NPCGuild(models.Model):
        ('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


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)

Answered By – niekas

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published