0

here is my model in django :

import os

def upload_location_buy(instance, filename):
    ext = filename.split('.')[-1]
    filename = '%s.%s' % (instance.name+"_"+str(random.randint(1000, 9999)), ext)
    print(os.path.join('uploads', filename))
    return os.path.join('uploads', filename)


class Buy(models.Model):
    pic_front = models.ImageField(blank=True, upload_to=upload_location_buy,default='')

When i try :

b = Buy(pic_front="appartement_a.jpg")
b.save()

it does nothing exception linking the current pic in the current path, so not using the function in the model.

And when i do :

b = Buy(pic_front=upload_location_buy("appartement_a.jpg"))
b.save()

it give me an error because it seems to need the instance.

TypeError: upload_location_buy() missing 1 required positional argument: 'filename'

How to create a buy object, giving it a picture and using the upload_location_buy whend doing it without the admin ?

When i upload a pic in the admin it works.

how to give it the instance name or do it correctly ?

this is this script :

import sys
import os
import django
from django.core.exceptions import ObjectDoesNotExist
sys.path.append("../../../testproject")
os.environ["DJANGO_SETTINGS_MODULE"] = "testproject.settings"
django.setup()

from on_plan.models import Buy

Buy.objects.all().delete()
b = Buy(pic_front=upload_location_buy("appartement_a.jpg"))
b.save()

The script is in the same directory as the file "appartement_a.jpg".

-on_plan/
-testproject/
-import_script.py
-appartement_a.jpg
-manage.py

if i do a :

file_to_save = open('appartement_a.jpg', 'r').read()
b = Buy(pic_front=file_to_save)
b.save()

i have a:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

if i do a :

file_to_save = open('appartement_a.jpg', 'rb').read()
b = Buy(pic_front=file_to_save)
b.save()

i have a:

AttributeError: 'bytes' object has no attribute '_committed'

the solution is here:

import requests
import urllib.parse
import sys
import os
import django
import csv
import time
import random
from django.core.exceptions import ObjectDoesNotExist
sys.path.append("../../../sample_estate")
os.environ["DJANGO_SETTINGS_MODULE"] = "sample_estate.settings"
django.setup()
from django.core.files.base import File
from on_plan.models import Buy

file_to_save = open('appartement_a.jpg', 'rb')
b = Buy(pic_front=File(file_to_save))
b.save()
Bussiere
  • 500
  • 13
  • 60
  • 119

1 Answers1

1

When you create a Buy object you need to pass file-obejct into pic_front attribute, but you try to pass only name of file.

from django.core.files.base import File

file_to_save = open('/path/to/appartement_a.jpg', 'r').read()
b = Buy(pic_front=File(file_to_save))
b.save()

If you get file from a form you may upload it like that:

b = Buy(pic_front=request.FILES['file'])
b.save()

Anyway pic_front expect to getting a file-object not string

More about this case

Nikita Zhuikov
  • 1,012
  • 8
  • 11