#32852: Attribute error for missing content_type on File object for modeladmin
change request
-------------------------------------+-------------------------------------
               Reporter:             |          Owner:  nobody
  aiventimptner                      |
                   Type:  Bug        |         Status:  new
              Component:  File       |        Version:  3.2
  uploads/storage                    |
               Severity:  Normal     |       Keywords:  content_type
           Triage Stage:             |      Has patch:  0
  Unreviewed                         |
    Needs documentation:  0          |    Needs tests:  0
Patch needs improvement:  0          |  Easy pickings:  0
                  UI/UX:  0          |
-------------------------------------+-------------------------------------
 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
 }}}

-- 
Ticket URL: <https://code.djangoproject.com/ticket/32852>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/056.c4f31883040b9b6f2eba5664319fd996%40djangoproject.com.

Reply via email to