django在模型中使用模型选择 [英] django use model choices in modelform
问题描述
我想知道如何在我的ModelForm中使用我的模型选择选项。
示例(模型):
$ b $
类别(
('COM','战斗'),
('CRA')
类别NPCGuild(models.Model) ,'Crafting'),
('WAR','Warfare'),
)
faction = models.ForeignKey(Faction)
category = models.CharField(max_length = 3 ,choices = CATEGORIES)
name = models.CharField(max_length = 63)
我的表单:
class NPCGuildForm(forms.ModelForm):
name = forms.CharField()
category = form.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']
正如你所看到的,我不知道我应该做什么来让我的选择从我的模型作为选择领域。也许可以使用ModelChoiceField来完成,但是如何获得选择呢?
有人可以帮我在这里
您应该在Meta类中指定模型,并自动生成字段:
class NPCGuildForm(forms.ModelForm):
class Meta:
model = NPCGuild
如果需要,您可以添加额外的表单字段。详细了解 ModelFroms 。
更新作为评论中提到的karthikr 。如果要在表单域中设置可用选项,则必须使用 forms.ChoiceField
,如下所示:
category = forms.ChoiceField(choices = NPCGuild.CATEGORIES)
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)
这篇关于django在模型中使用模型选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!