代码之家  ›  专栏  ›  技术社区  ›  Adam Nelson

缩小Django形式的选择范围

  •  3
  • Adam Nelson  · 技术社区  · 17 年前

    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
    

    CampaignForm(initial={'name':'Default Name'})

    3 回复  |  直到 12 年前
        1
  •  6
  •   int_ua PhoebeB    11 年前

    我是这样限制显示的选项的:

    在forms.py中添加一个 初始化

    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
    
        2
  •  1
  •   Soviut    17 年前

    选项仅适用于列表,不适用于CharFields。你需要做的是创建一个 custom validator on clean() .

    在forms.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
    
        3
  •  1
  •   Adam Nelson    17 年前

    class CampaignForm(ModelForm):
        type = forms.ModelChoiceField(queryset=OtherModel.objects.filter(type__id=1))
        class Meta:
            model = Campaign
    

    我现在不确定如何传递“1”,但即使需要硬编码,这也足够了。此外,它让Django完成了大部分繁重的工作。

    @soviut我将把字段名更改为非保留字。谢谢你的提醒。