﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
32852	Attribute error for missing content_type on File object for modeladmin change request	Aiven Timptner	nobody	"I've got a model with a FileField and the corresponding admin page created with modeladmin. To validate the file type and only allow PDFs I wrote a custom validator which checks the content_type attribute on user (staff) uploads. When objects are created or the file itself get changed everything works as expected. But if I change some others fields on the model I receive an AttributeError.

{{{#!python
def validate_file_extension(value: File):
    """"""Check if uploaded file content is pdf""""""
    if value.file.content_type != 'application/pdf':
        raise ValidationError(""Only PDF are allowed"")


def user_directory_path(instance: File, filename: str) -> str:
    """"""Return a unix-like storage path as string with random file name""""""
    filename = token_urlsafe(5) + '.pdf'
    filepath = f""jobs/{filename}""
    if Job.objects.filter(file=filepath).exists():
        return user_directory_path(instance, filename)
    return filepath


class Job(models.Model):
    title = models.CharField(max_length=250)
    description = models.TextField()
    file = models.FileField(upload_to=user_directory_path, validators=[validate_file_extension], blank=True, null=True)
    expired_on = models.DateTimeField(blank=True, null=True)
    created_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)
}}}

For now I solved it by ignoring AttributeErrors on validation

{{{#!python
class Job(models.Model):
    title = models.CharField(max_length=250)
    description = models.TextField()
    file = models.FileField(upload_to=user_directory_path, validators=[validate_file_extension], blank=True, null=True)
    expired_on = models.DateTimeField(blank=True, null=True)
    created_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)

    def clean_fields(self, exclude=None):
        try:
            super().clean_fields(exclude=exclude)
        except AttributeError:
            # Handle missing content_type on file object
            pass
}}}"	Bug	closed	File uploads/storage	3.2	Normal	invalid	content_type		Unreviewed	0	0	0	0	0	0
