Пример #1
0
    def test_formfield_required_false(self):
        form_field = FormField(form=self.TestFormWithRequiredField,
                               required=False)

        # TEST: valid input
        valid_val = {'name': 'blah'}
        self.assertEqual(valid_val, form_field.clean(valid_val))

        # TEST: required=False - empty values return {}
        for empty_val in EMPTY_VALUES:
            self.assertEqual({}, form_field.clean(empty_val))
Пример #2
0
class AlbumForm(Form):
    title = fields.CharField(max_length=100)
    year = fields.IntegerField()
    artist = FormField(form=ArtistForm)
    songs = FormFieldList(form=SongForm)
    type = EnumField(enum=Album.AlbumType, required=True)
    metadata = DictionaryField(fields.DateTimeField())

    def clean_year(self):
        if self.cleaned_data['year'] == 1992:
            raise ValidationError("Year 1992 is forbidden!", 'forbidden-value')
        return self.cleaned_data['year']

    def clean(self):
        if (self.cleaned_data['year']
                == 1998) and (self.cleaned_data['artist']['name']
                              == "Nirvana"):
            raise ValidationError("Sounds like a bullshit",
                                  code='time-traveling')
        return self.cleaned_data

    def fill_artist(self, obj, value: dict):
        return Artist(name=value.get('name'),
                      genres=value.get('genres'),
                      members=value.get('members'))
Пример #3
0
class EntryForm(Form):
    language_code = forms.CharField(max_length=3)
    author_id = forms.ModelChoiceField(queryset=Author.objects.all(),
                                       required=False)
    author = FormField(AuthorForm, required=False)
    category_ids = forms.ModelMultipleChoiceField(
        queryset=Category.objects.all(), required=False)
    contributors = FormFieldList(AuthorForm, required=False)
    contributor_ids = forms.ModelMultipleChoiceField(
        queryset=Author.objects.all(), required=False)
    feeds = forms.ModelMultipleChoiceField(queryset=Feed.objects.all(),
                                           required=False)
    categories = FormFieldList(CategoryForm, required=False)
    title = forms.CharField(max_length=255)
    summary = forms.CharField(required=False)
    content = forms.CharField(required=False)
    acquisitions = FormFieldList(AcquisitionForm, required=False)
    identifiers = DictionaryField(
        required=False,
        validators=[AvailableKeysValidator(keys=settings.OPDS['IDENTIFIERS'])],
        value_field=forms.CharField(max_length=100))
    image = ImageField(max_length=settings.OPDS['IMAGE_UPLOAD_MAX_SIZE'],
                       mime=settings.OPDS['IMAGE_MIME'],
                       required=False)

    def clean_language_code(self) -> Language:
        language = Language.objects.filter(
            Q(alpha2=self.cleaned_data['language_code'])
            | Q(alpha3=self.cleaned_data['language_code'])).first()

        if not language:
            raise ValidationError(
                "Language not found. Use valid alpha2 or alpha3 code.",
                'not-found')

        return language

    def clean(self):
        if 'author_id' in self.cleaned_data.keys(
        ) and 'author' in self.cleaned_data.keys():
            raise ValidationError(
                _("You have to provide author_id or author object (not both)"),
                'invalid')

        if 'category_ids' in self.cleaned_data.keys(
        ) and 'categories' in self.cleaned_data.keys():
            raise ValidationError(
                _("You have to provide category_ids or categories object (not both)"
                  ), 'invalid')

        if 'contributor_ids' in self.cleaned_data.keys(
        ) and 'contributors' in self.cleaned_data.keys():
            raise ValidationError(
                _("You have to provide contributor_ids or contributors object (not both)"
                  ), 'invalid')

        return self.cleaned_data
Пример #4
0
    def test_formfield_required(self):
        form_field = FormField(form=self.TestFormWithRequiredField)

        # TEST: valid input
        valid_val = {'name': 'blah'}
        self.assertEqual(valid_val, form_field.clean(valid_val))

        # TEST: invalid input (values the FormField considers invalid)
        invalid_vals = [
            '0', 1,
            datetime.datetime.now(), 'blah', {'blah'}, ['blah']
        ]
        expected_error = "({'name': [ValidationError(['Invalid value'])]}, None, None)"
        for invalid_val in invalid_vals:
            with self.assertRaisesMessage(RequestValidationError,
                                          expected_error):
                log_input(invalid_val)
                form_field.clean(invalid_val)

        # TEST: required=True, form WITH required field - invalid input (empty value)
        invalid_val = {'name': None}
        expected_error = "({'name': [ValidationError(['This field is required.'])]}, None, None)"
        with self.assertRaisesMessage(RequestValidationError, expected_error):
            form_field.clean(invalid_val)

        # TEST: required=True, form WITH required field - invalid input (unexpected dict key)
        invalid_val = {'unexpected key': 'blah'}
        expected_error = "({'name': [ValidationError(['This field is required.'])]}, None, None)"
        with self.assertRaisesMessage(RequestValidationError, expected_error):
            form_field.clean(invalid_val)

        # TEST: required=True, form WITHOUT required field - unexpected dict key returns blanks with keys
        # Django returns a normalized empty value when required=False rather than raising ValidationError
        invalid_val = {'unexpected key': 'blah'}
        form_field_no_required_fields = FormField(
            required=False, form=self.TestFormWithoutRequiredField)

        self.assertEqual({}, form_field_no_required_fields.clean(invalid_val))

        # TEST: required=True - empty values throw an error
        for empty_val in EMPTY_VALUES:
            with self.assertRaisesMessage(ValidationError,
                                          "['This field is required.']"):
                log_input(empty_val)
                form_field.clean(empty_val)