缩小Django形式的选择范围
我有一个这样的模型:缩小Django形式的选择范围,django,django-forms,Django,Django Forms,我有一个这样的模型: CAMPAIGN_TYPES = ( ('email','Email'), ('display','Display'), ('search','Search'), ) class Campaign(models.Model): name = models.CharField(max_length=255) type
CAMPAIGN_TYPES = (
('email','Email'),
('display','Display'),
('search','Search'),
)
class Campaign(models.Model):
name = models.CharField(max_length=255)
type = models.CharField(max_length=30,choices=CAMPAIGN_TYPES,default='display')
和一份表格:
class CampaignForm(ModelForm):
class Meta:
model = Campaign
是否有办法限制“类型”字段的可用选项?我知道对于单个值字段我可以这样做:
activityform(initial={'name':'defaultname'})
,但对于选项集,我找不到任何方法可以这样做。选项仅用于列表,而不是字符字段。您需要做的是创建一个
格式为.py
CAMPAIGN_TYPES = ('email', 'display', 'search')
# this would be derived from your Campaign modelform
class EnhancedCampaignForm(CampaignForm):
# override clean_FIELD
def clean_type(self):
cleaned_data = self.cleaned_data
campaign_type = cleaned_data.get("type")
# strip whitespace and lowercase the field string for better matching
campaign_type = campaign_type.strip().lower()
# ensure the field string matches a CAMPAIGN_TYPE, otherwise
# raise an exception so validation fails
if not campaign_type in CAMPAIGN_TYPE:
raise forms.ValidationError("Not a valid campaign type.")
# if everything worked, return the field's original value
return cleaned_data
这似乎是覆盖“类型”字段的最佳方法:
class CampaignForm(ModelForm):
type = forms.ModelChoiceField(queryset=OtherModel.objects.filter(type__id=1))
class Meta:
model = Campaign
我现在不知道如何通过'1',但这将是足够好的,即使它需要硬编码。此外,它还可以让Django完成大部分繁重的工作
@soviut I将字段名更改为非保留字。感谢您的提醒。这就是我限制显示选项的方式: 在forms.py中,为表单添加一个init方法
class TaskForm(forms.ModelForm):
....
def __init__(self, user, *args, **kwargs):
'''
limit the choice of owner to the currently logged in users hats
'''
super(TaskForm, self).__init__(*args, **kwargs)
# get different list of choices here
choices = Who.objects.filter(owner=user).values_list('id','name')
self.fields["owner"].choices = choices
您可能需要更改字段名,因为“type”在Python中是一个保留关键字。另外,您是否有理由不将活动类型设置为ChoiceField而不是CharField?活动是一个模型,因此ChoiceField不是一个选项。我不确定这到底是如何工作的。我正在尝试在表单的选择列表上显示“email”和“display”。如果您能帮助我将变量传递给type\uu id,我将不胜感激。在形式内部,没有“自我”。我不知道里面有什么可以访问。这可以在实例化时使用:form=activityform()form.fields['type'].choices=TestModel.objects.\filter(filtercriterion\uu id=1).values\u list('id','name')来完成。这个页面真的很有帮助: