Django form narrowing down

I have a model like:

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')

And the form:

class CampaignForm(ModelForm):
    class Meta:
        model = Campaign

Is there a way to limit which options are available for a type field? I know that for one field of value I can do: CampaignForm(initial={'name':'Default Name'})but I cannot find a way to do this for a selection set.

+3
source share
3 answers

Here's how I limited the displayed options:

In forms.py add the init method for your form

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
+6
source

The selection is only for lists, not for CharFields. What you need to do is create a custom validator onclean() .

in 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 original value
        return cleaned_data
+1
source

, , :

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

, "1", , . , Django .

@soviut I will change the field name to an unreserved word. Thanks for the heads.

+1
source

Source: https://habr.com/ru/post/1717376/


All Articles