I tried to implement custom validation error in django

I have wrote this validators.py file:

from django.core.exceptions import ValidationError
import os

def allow_only_images_validator(value):
    ext = os.path.splitext(value.name)[1]
    print(ext)
    valid_extensions = ['.png', '.jpg', '.jpeg']
    if not ext.lower() in valid_extensions:
        raise ValidationError("Unsupported file extension. Allowed extensions: " +str(valid_extensions))

This is my forms.py file:

class userProfileForm(forms.ModelForm):
    class Meta:

        profile_picture = forms.FileField(widget=forms.FileInput(attrs={'class': 'btn btn-info'}), validators=[allow_only_images_validator])
        cover_photo = forms.FileField(widget=forms.FileInput(attrs={'class': 'btn btn-info'}), validators=[allow_only_images_validator])

But this error is not showing in my template. The SS is here: enter image description here

Can anybody help me on how do I fix it?

The issue is that you're defining form fields profile_picture and cover_photo inside the Meta class, which is incorrect. In Django, the Meta class is used to specify metadata such as the model to use and the fields to include - not to define form fields. Your working code should look like this:

class userProfileForm(forms.ModelForm):
        profile_picture = forms.FileField(widget=forms.FileInput(attrs={'class': 'btn btn-info'}), validators=[allow_only_images_validator])
        cover_photo = forms.FileField(widget=forms.FileInput(attrs={'class': 'btn btn-info'}), validators=[allow_only_images_validator])
        class Meta:
            model = UserProfile   # name of your model
            fields = ['profile_picture', 'cover_photo',]  # Add other fields as needed
Вернуться на верх