我正在尝试将多选小部件添加到与char字段对应的管理视图中。
models.py
class Campaign(models.Model):
name = models.CharField(max_length=128)
start_date = models.DateTimeField(default=timezone.now)
end_date = models.DateTimeField(blank=True, null=True)
budget = models.IntegerField()
target = models.IntegerField()
component_choices = models.CharField(max_length=128, null=True, blank=True)
admin.py
class CampaignAdmin(admin.ModelAdmin):
fieldsets = (
('Main', {
'fields': ('name', ('start_date', 'end_date',),),
}),
('Budget', {
'fields': ('budget', 'target',),
}),
('Payment', {
'fields': ('payment_terms', 'payment_initial', 'payment_per_mvm'),
}),
)
form = ComponentChoicesForm
admin.site.register(Campaign, CampaignAdmin)
forms.py
class ComponentChoicesForm(ModelForm):
component_type_choices = tuple(
(x.id, str(x))
for x in ComponentType.objects.all()
)
class Meta:
model = ComponentType
fields = '__all__'
available_components = forms.MultipleChoiceField(
choices=component_type_choices)
但是,上述代码只显示fieldsets
而不显示ComponentTypeChoices
表单。我的目的是让用户从forms.py
admin.py
中生成的选项中进行选择,以便填充Campaign.component_choices
字段。
答案 0 :(得分:0)
您已为其他模型创建了表单,并在Campaign模型管理中使用了该表单。您应该为Campaign
模型而不是ComponentType
创建模型表单。
您的表单和模型管理员应该是这样的,
forms.py
class CampaignForm(ModelForm):
class Meta:
model = Campaign
fields = '__all__'
OPTIONS = (('a', 'A'),('b', 'B'),('c', 'C'))
available_components = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
choices=OPTIONS)
admin.py
class CampaignAdmin(admin.ModelAdmin):
form = CampaignForm