简体   繁体   中英

Django: Slicing form data before “form.is_valid”

I have a ModelForm, which saves and creates a new object for my class Person . This class Person has an attr called is_adult . Its value is a model.CharField with a max_length=1 , where I save only values Y or N (Yes/No).

The problem is that this attr is rendered as a Select HTML field. In this Select field, the available choices are "Yes" and "No", therefore when the form is sent as a POST method it comes with a value of 2-3 length CharField, but its Model attr has a max_length of 1, so I need to slice those two options before checking if form.is_valid() . Otherwise the form is not accepted because it is posting with a value of 2-3 chars and it's expecting 1 char.

models.py:

class Person(models.Model):
    is_adult = models.CharField(max_length=1, null=False, choices=ADULT_CHOICES, default='N')

choices.py:

ADULT_CHOICES= (
        (0, 'No'),
        (1, 'Yes'),
)

forms.py:

class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = ["is_adult"]
        widgets = {
            'is_adult': forms.Select(attrs={'class': 'form-control'}),
        }
        labels= {
            'is_adult': 'Is an adult?',
        }

And of course views.py is expecting 'Y' or 'N', and not 'Yes' or 'No'. I tried to slice its string with the Python syntaxis, but I couldn't get the form field value before it gets rejected in "form.is_valid". Any solution? Thanks!

Marked as duplicate, but you should use a choice form field .

Change your forms.py to the following:

class PersonForm(forms.ModelForm): 
    class Meta:
        model = Person
        fields = ["is_adult"]
        labels= {
            'is_adult': 'Is an adult?',
        }

The default behavior of the model form should use a form.ChoiceField which should automatically set your select options (in your HTML) to the correct 'Y' and 'N' values.

You should not need to slice anything, as Django should handle this for you.

When a ChoiceField is used your HTML should be rendered like this (note the option values ):

<select>
  <option value="Y">Yes</option>
  <option value="N">No</option>
</select>

See duplicate question: How do I use Django's form framework for select options?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM