Saving files to upload field in Django using a Python script

Twitch

Building an application to list reports for inspections. The actual inspection report is going to be made available for download. Saving the reports to the database using django-db-file-storage.

Lots of records to process, so writing a script to do everything in bulk. Testing in the manage.py shell throws an error.

from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from inspections.models import InspectionInformation, RestaurantInformation

file = open('/docs/Data/2011/12/12-07-11_1498.pdf', 'r').read()

InspectionInformation(
                insp_rest_permit=RestaurantInformation.objects.get(rest_permit=int('1814')),
                insp_date='2011-12-12',
                insp_score='100',
                insp_inspector='Philip',
                insp_report=default_storage.save('report.pdf', ContentFile(file))
            ).save()

Traceback

Traceback (most recent call last):
  File "<console>", line 6, in <module>
  File "/venv/lib/python2.7/site-packages/django/core/files/storage.py", line 48, in save
    name = self.get_available_name(name)
  File "/venv/lib/python2.7/site-packages/django/core/files/storage.py", line 74, in get_available_name
    while self.exists(name):
  File "/venv/lib/python2.7/site-packages/db_file_storage/storage.py", line 77, in exists
    model_class_path, content_field, filename_field, mimetype_field, filename = name.split('/')
ValueError: need more than 1 value to unpack

Models

from django.db import models


class RestaurantInformation(models.Model):
    rest_permit = models.IntegerField(unique=True, verbose_name='Permit')
    rest_name = models.CharField(max_length=200, verbose_name='Name')
    rest_address = models.CharField(max_length=200, verbose_name='Address')
    rest_city = models.CharField(max_length=100, verbose_name='City')
    rest_zip = models.IntegerField(verbose_name='Zip Code')
    rest_owner = models.CharField(max_length=200, verbose_name='Owner')
    rest_latitude = models.CharField(max_length=40, verbose_name='Latitude')
    rest_longitude = models.CharField(max_length=40, verbose_name='Longitude')

    class Meta:
        ordering = ['rest_name']

    def __unicode__(self):
        return self.rest_name + ', ' + self.rest_address + ', ' + self.rest_city


class InspectionInformation(models.Model):
    insp_rest_permit = models.ForeignKey(RestaurantInformation, null=False, to_field='rest_permit')
    insp_score = models.DecimalField(verbose_name='Score', decimal_places=2, max_digits=5)
    insp_date = models.DateField(verbose_name='Date')
    insp_inspector = models.CharField(max_length=200, verbose_name='Inspector')
    insp_report = models.FileField(upload_to='restaurants.InspectionFile/bytes/filename/mimetype',
                                   blank=True, null=True, verbose_name='Inspection Report')

    class Meta:
        unique_together = ("insp_rest_permit", "insp_score", "insp_date")
        ordering = ['insp_date']


class InspectionFile(models.Model):
    bytes = models.TextField()
    filename = models.CharField(max_length=255)
    mimetype = models.CharField(max_length=50)
Charlie

1.It looks like db_file_storage.storage.save() expects their custom format specified to be used with the model plus the filename e.g. "console.ConsolePicture/bytes/filename/mimetype" + filename.

So for your example instead of

'report.pdf' 

it would be

'restaurants.InspectionFile/bytes/filename/mimetype/report.pdf'

I looked at the documentation and it isn't clear why it's being done this way as this violates DRY by making you enter the same thing twice, but they use the same format throughout the DatabaseFileStorage class.

2.It also looks like there's a bug in the save method (line 60) where

mimetype = content.file.content_type

should be changed to

mimetype = content.content_type

And the file you pass it should be something with a content_type attribute so probably a Django SimpleUploadedFile:

from django.core.files.uploadedfile import SimpleUploadedFile
file_ = SimpleUploadedFile('report.pdf', open('/docs/Data/2011/12/12-07-11_1498.pdf', 'r').read())  

The reason I think this is a bug is that when I tried passing in a mock object that looked like "content.file.content_type" I got a Python core library exception later on.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Django Form not saving when using a custom field

From Dev

upload files to gdrive using a tool but in a script

From Dev

How to upload multiple images in Django using Dropzone and saving path dynamically ?

From Dev

JS files upload queue using Django block

From Dev

Saving files using writeToFile

From Dev

Boolean field not saving in Django form

From Dev

Saving OnetoOne field manually in django

From Dev

Django saving in a model with User field

From Dev

Saving files with python codecs

From Dev

Upload image into gravatar using python django

From Dev

Django formset not saving my files

From Dev

Is there a way to upload files using the browsable API in Django REST framework?

From Dev

Upload and rename two different files in two different folders using django?

From Dev

Files getting renamed while using file upload in django

From Dev

Django : Image upload "This field is required"

From Dev

bash script to upload files to sftp

From Dev

Saving a struct in C using Files

From Dev

Saving a struct in C using Files

From Dev

Copy files to a network path using python script

From Dev

Deleting Windows Temp Files using python script

From Dev

Reading input files using python script

From Dev

Upload files using CKeditor

From Dev

Upload files using CKeditor

From Dev

Django Rest Framework add field to model before saving in viewset using ModelSerializer

From Dev

Django Formset Issue On Select Field and Saving?

From Dev

django updating foreignKey field before saving

From Dev

Saving Django formset with Many to Many Field

From Dev

Django: ValueError when saving an instance to a ForeignKey Field

From Dev

Create a folder (if not exists) on google drive and upload a file to it using Python script

Related Related

  1. 1

    Django Form not saving when using a custom field

  2. 2

    upload files to gdrive using a tool but in a script

  3. 3

    How to upload multiple images in Django using Dropzone and saving path dynamically ?

  4. 4

    JS files upload queue using Django block

  5. 5

    Saving files using writeToFile

  6. 6

    Boolean field not saving in Django form

  7. 7

    Saving OnetoOne field manually in django

  8. 8

    Django saving in a model with User field

  9. 9

    Saving files with python codecs

  10. 10

    Upload image into gravatar using python django

  11. 11

    Django formset not saving my files

  12. 12

    Is there a way to upload files using the browsable API in Django REST framework?

  13. 13

    Upload and rename two different files in two different folders using django?

  14. 14

    Files getting renamed while using file upload in django

  15. 15

    Django : Image upload "This field is required"

  16. 16

    bash script to upload files to sftp

  17. 17

    Saving a struct in C using Files

  18. 18

    Saving a struct in C using Files

  19. 19

    Copy files to a network path using python script

  20. 20

    Deleting Windows Temp Files using python script

  21. 21

    Reading input files using python script

  22. 22

    Upload files using CKeditor

  23. 23

    Upload files using CKeditor

  24. 24

    Django Rest Framework add field to model before saving in viewset using ModelSerializer

  25. 25

    Django Formset Issue On Select Field and Saving?

  26. 26

    django updating foreignKey field before saving

  27. 27

    Saving Django formset with Many to Many Field

  28. 28

    Django: ValueError when saving an instance to a ForeignKey Field

  29. 29

    Create a folder (if not exists) on google drive and upload a file to it using Python script

HotTag

Archive