简体   繁体   中英

Run Django script on Windows to create models on Linux

I'm running a data crawler on a Windows 7 machine. I'm inserting the results remotely to my Django 1.10 project on my CentOS 7 server. I have a copy of the Django project on both machines. This works fine for all fields in the model, except the ImageField.

Here is the part of my script that does the saving.

m = Object(strings=strings)
m.save()
image_content = ContentFile(requests.get(image_url).content, id + '.jpg')
m.image_file.save("C:\\Users\\Me\\Documents\\mysite.com\\imgs\\" + id + ".jpg", image_content)
m.save()

The image field is declared as:

image_file = models.ImageField(upload_to='avatars/', null=True, default=None)

My settings.py file on the Windows machine has the line:

MEDIA_ROOT = "/var/www/mysite.com/myproj/images/"

On the first run, there are no errors but the image_feild on the server is set to "."

On the second run, the error is:

IOError: C:\\var\\www\\mysite.com\\myproj\\images exists and is not a directory.

So this is being created on the Windows machine, but I want the MEDIA_ROOT to be used as the destination directory on the server.

Either use os module.

import os
if os.name == 'nt':
    # Windows code.
else:
    # Unix code.

Or user relative paths.

# In settings.
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, '../media_root')

# In other places.
mage_file.save(os.path.join(MEDIA_ROOT, '/dir_name/file_name.jpg'), image_content)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM