6

I want to run the following script to pre-populate a model of mine with names etc...But I get an error. The script is

first_names = first_names.split('\n')
last_names = last_names.split('\n')
phones=[str(i) for i in range(2310000000,2310999999, 1563)]
emails = ['test%s@test.com' %i for i in range(0,144)]

import os
os.environ['DJANGO_SETTINGS_MODULE']='project.settings'

from customer.models import Customer
from django.contrib.auth.models import User

users = User.objects.all()

if __name__ == "__main__":
    for i in range(10):
        customer = Customer(first_name=choice(first_names), last_name=choice(last_names),
                        telephone=choice(phones),email=choice(emails), creator=choice(users))
        customer.save()

and the error is

Traceback (most recent call last):
  File "populatedb.py", line 431, in <module>
    from customer.models import Customer
ImportError: No module named customer.models

the dir_tree is (if I can "draw" it correctly)

-project_dir
|
|--customer
|--|
   |--models.py(etc...)
|
|--project(the settings file is here)
|--
|--another_app
|--scripts (here is my python script)
Apostolos
  • 7,763
  • 17
  • 80
  • 150
  • Where is the script itself located? – bozdoz Nov 26 '13 at 15:03
  • Not really something to do with the question, but there's a UNIX command line tool called `tree` that makes drawing directory structures a lot easier. Try doing `sudo apt-get install tree` if you are on linux. – wdh Nov 26 '13 at 15:21
  • Unfortunatelly I am on windows at work...i do have it on my Linux box at home (the tree command i mean). – Apostolos Nov 26 '13 at 15:44
  • Possible duplicate of [Django script to access model objects without using manage.py shell](http://stackoverflow.com/questions/8047204/django-script-to-access-model-objects-without-using-manage-py-shell) – Ciro Santilli OurBigBook.com May 13 '16 at 14:11

3 Answers3

6

You may append your sys path to your script like:

import sys
sys.path.append('/path/to/your/djangoproject/')

Hope this helps.

Jingo
  • 3,200
  • 22
  • 29
4

My script worked after I added these lines before setting as os.environ var project_settings

script_path = os.path.dirname(__file__)
project_dir = os.path.abspath(os.path.join(script_path,'..','..','project_folder'))
sys.path.insert(0, project_dir)
os.environ['DJANGO_SETTINGS_MODULE']='rhombus.settings'

Thank you all!

Apostolos
  • 7,763
  • 17
  • 80
  • 150
4

You can also create custom django-admin commands and execute them using manage.py: https://eli.thegreenplace.net/2014/02/15/programmatically-populating-a-django-database https://docs.djangoproject.com/en/2.1/howto/custom-management-commands/

Ivan
  • 472
  • 4
  • 15