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

有帮助吗?

解决方案

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)

其他提示

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()
        }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top