Hans de Jong
Hans de Jong

Reputation: 2078

django use model choices in modelform

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?

Upvotes: 5

Views: 16184

Answers (2)

Ahmed
Ahmed

Reputation: 11

I will do it differently, just keep in mind that you can generate the whole form from the model automatically, without having to create each field again, and this is one of the beauty of Django which save you time, here is how I will do it, in your form file:

class NPCGuildForm(forms.ModelForm):
    class Meta:
        model = NPCGuild
        fields = ['name', 'category', 'faction']

        widgets = {
            'category' : forms.Select()
        }

Upvotes: 0

niekas
niekas

Reputation: 9097

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)

Upvotes: 9

Related Questions