Home > Net >  Validate a field of form that allows multiple photos upload
Validate a field of form that allows multiple photos upload

Time:11-13

I have a custom form that allows to upload multiple photos which I'm using in UserAdmin model. Also I have my own validator for a field in User model. I was trying to make a validator for the field of my form by overriding clean method, but clean method made my custom validator in User model unworkable, so it means my validator for a field in User model became useless because clean method in forms.py works for everything. I've tried to go through this answer but it didn't help me. How can I make each validator work for the field that they are intended for?

forms.py

from django import forms
from django.utils.safestring import mark_safe

from .models import UserImage


class PhotoUploadForm(forms.ModelForm):
    photo = forms.FileField(
        widget=forms.ClearableFileInput(attrs={'multiple': True}),
        required=False,
        help_text='Необходимо количество фото - 10',
        label=mark_safe("<strong style='color:black'>Фото</strong>")
        )

    def clean_photos(self):
        photos = self.files.getlist('photo')
        if len(photos) != 10:
            raise forms.ValidationError(
                {'photo': f'Вы попытались загрузить {len(photos)} фотографий'})
        return photos

    class Meta:
        model = UserImage
        fields = '__all__'

admin.py

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    form = PhotoUploadForm

models.py

class User(models.Model):
    first_name = models.CharField(
        verbose_name='Имя',
        max_length=40,
        )
    last_name = models.CharField(
        verbose_name='Фамилия',
        max_length=40
        )
    rfid_mark = models.CharField(
        verbose_name='RFID',
        max_length=10,
        unique=True,
        help_text='RFID должен состоять из 10 символов',
        error_messages={
            'unique': 'Такой RFID уже существует'
        },
        validators=[validate_rfid_length]
        )

CodePudding user response:

If the field you want to clean is called photo then the clean method you need is called clean_photo() not clean_photos()

  • Related