Run the script to populate django db

I want to run the following script to pre-populate my model with names, etc. But I get an error message. script -

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 mistake

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

dir_tree (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) 
+6
source share
2 answers

You can add your sys path to your script as:

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

Hope this helps.

+5
source

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' 

Thanks everyone!

+3
source

Source: https://habr.com/ru/post/958871/


All Articles