django use model choices in modelform

北战南征 提交于 2019-12-13 18:14:18

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/20685155/django-use-model-choices-in-modelform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!