1

Any idea how to load data that has models with ImageField in django? I cannot use fixtures for this as there’s no way to serialize images into the fixtures files.

I’m trying to use factory-boy which works very well for tests but I cannot see how to run it as a standalone script because there’s no django management command for it.

Is python manage.py shell < myscript.py a good approach to handle this or there’s a better way?

Note that I’m using a bucket for file storage with salted filenames, and I have signals that do stuff like indexing into Elasticsearch which I need to keep. and fixtures don’t do this.

abdelhalimresu
  • 417
  • 6
  • 15
  • Do you have your image file in place and know filename in advance? – Slam Feb 11 '19 at 10:36
  • @Slam No. I'm using salted filenames using `uuid` and I'm planing to download random images from the internet using https://source.unsplash.com/random – abdelhalimresu Feb 11 '19 at 10:38
  • Please check https://stackoverflow.com/questions/1308386/programmatically-saving-image-to-django-imagefield . Does it fit your case? – Slam Feb 11 '19 at 10:45
  • Not really, I don't have problem with storing image programmatically. the only problem is how I can run my script within the context of the django app and still benefit from the functionalities I wrote in post save signals. I think I should create a management command for this purpose. – abdelhalimresu Feb 11 '19 at 10:51

1 Answers1

2

Well, the question is actually about having django env for your script, I've misunderstood the question.

  1. You may use shell < script.py, viable one-timer
  2. Make your custom management command. Ok if this is something regular, main benefit is "maintainability" — intention will be more clear for other people, plus manage.py integrations with IDE may be good
  3. Your script may setup django env itself — same as manage.py shell does, there's not much of black magic, something like

    import os, django
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
    django.setup()
    
Slam
  • 8,112
  • 1
  • 36
  • 44
  • The 3rd option looks good, I can also do it this way https://docs.djangoproject.com/en/1.9/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage But I think I'll go with creating a management command because I'll probably need to add some args to customize the script. – abdelhalimresu Feb 11 '19 at 11:06
  • Yup, if writing command is not a big deal for you, it worth going that way – Slam Feb 11 '19 at 11:08