[英]Show multiple choices to admin in django
我想向管理員展示多種選擇,以便他一次可以從這些選擇中選擇 select 多於一個。 我可以使用復選框字段來做到這一點。我已經嘗試過了,但它沒有顯示復選框,而是顯示了下拉選項列表。
這是我的代碼。
模型.py
class segmentation_Rules(models.Model):
Segmentation_Rules_CHOICES = (
(1, 'At least one order'),
(2, 'Have reward points'),
)
Rules =models.CharField(max_length=100, blank=True,verbose_name="Select rules for customer segmentation",choices=Segmentation_Rules_CHOICES)
forms.py
class Segmentation_Form(ModelForm):
Rules = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple)
管理員.py
class MyAdmin(admin.ModelAdmin):
form = Segmentation_Form
所以請告訴我一些方法,以便管理員可以選擇 select 多個字段。
編輯:
如果我從模型中刪除選擇並將它們定義到 forms 中,那么只有一個文本字段顯示給管理員,沒有選擇。
Segmentation_Rules_CHOICES = (
(1, 'At least one order'),
(2, 'Have reward points'),
)
class Segmentation_Form(ModelForm):
Rules = forms.MultipleChoiceField(choices=Segmentation_Rules_CHOICES, widget=forms.CheckboxSelectMultiple())
class Meta:
model=segmentation_Rules
您需要從models.py中的 model 字段定義中刪除choices
參數,並將choices
字段添加到forms.py的Rules
表單字段中。 像這樣:
模型.py
class segmentation_Rules(models.Model):
Segmentation_Rules_CHOICES = (
(1, 'At least one order'),
(2, 'Have reward points'),
)
Rules = models.CharField(max_length=100, blank=True, verbose_name="Select rules for customer segmentation")
forms.py
class Segmentation_Form(ModelForm):
Rules = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), choices=models.segmentation_Rules.Segmentation_Rules_CHOICES)
是的,你可以這么做。 您需要使用帶有CheckboxSelectMultiple小部件的MultipleChoiceField字段來執行此操作。 我認為您做得對,但也許您在小部件中忘記了()
?
class Segmentation_Form(forms.Form):
Rules = forms.MultipleChoiceField(choices= Segmentation_Rules_CHOICES, widget=forms.CheckboxSelectMultiple())
def clean_Rules(self):
if len(self.cleaned_data['Rules']) > 3:
raise forms.ValidationError('Select no more than 3.')
return self.cleaned_data['Rules']
我已經拋出了一個驗證方法。 您可以在其中限制所選選項的數量。
我正在使用它並且它工作正常
Rules = forms.MultipleChoiceField(choices=mychoices, widget=forms.CheckboxSelectMultiple)
我認為您在CheckboxSelectMultiple
發送時不需要()
它存儲用逗號分隔的選項。
models.py
和admin.py
原樣
forms.py
from my_project.model import segmentation_Rules
class Segmentation_Form(ModelForm):
Rules = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=segmentation_Rules.Segmentation_Rules_CHOICES, required=False)
def __init__(self, *args, **kwargs):
super(Segmentation_Form, self).__init__(*args, **kwargs)
if kwargs.get('instance'):
self.initial['Rules'] = eval(self.initial['Rules'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.