-2

This is my model.

class Product(models.Model)
    id = models.AutoField(max_length=10,  primary_key=True)
    name = models.CharField(max_length=60)
    summary = models.TextField(max_length=200)
    image = models.FileField(upload_to='product_images', blank=True)

I know how to import data from csv in django model. But I also have image field here.

Can I upload files to models from the method of adding data to models from csv? How?

I am using this method for importing them: http://mitchfournier.com/2011/10/11/how-to-import-a-csv-or-tsv-file-into-a-django-model/

I have images stored in a folder in my system.

Abhishek Balani
  • 3,827
  • 2
  • 24
  • 34

2 Answers2

2

FileField is just a reference to a file. It does not put a file into the database as is sometimes mistakenly believed.

Assuming that you have already got the code written for reading through the CSV and fetching the location of the file. Then all you need to do is to follow the example given in FileField.save()

This method takes a filename and file contents and passes them to the storage class for the field, then associates the stored file with the model field. If you want to manually associate file data with FileField instances on your model, the save() method is used to persist that file data.

Takes two required arguments: name which is the name of the file, and content which is an object containing the file’s contents.

Something like this:

p = Product()
p.image.save('name from csv',open('path from csv'))
e4c5
  • 52,766
  • 11
  • 101
  • 134
0

I solved it by saving the name of the image in the csv and just uploading the name in the field like this:

...
product.image = "product_images" + namefromcsv 

then I uploaded all the images in the media folder inside product_images .

And it worked very well.

I tried uploading the image with product.image.save() option with File class but it didn't work for me.

Abhishek Balani
  • 3,827
  • 2
  • 24
  • 34