2

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.