###### This is a script named "template.py" for establishing django settings in any other script
def myfunc():
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
from django.db import connection
# Ensure settings are read
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
###### This is a script named "write.py" that is inside a django app : run python write.py to execute
# Django specific settings
from template import myfunc
myfunc() # First apply the settings, otherwise myapp will not be recognised
import django
from datetime import date
from myapp.models import User, Teacher, Student, Course, Lesson, Enrollment
def insert_data():
# Inserting teachers (and also users)
teacher1 = Teacher.objects.create(username='teacher1', dob=date(1980, 1, 1), sex='Male', position='Math Teacher')
teacher2 = Teacher.objects.create(username='teacher2', dob=date(1985, 5, 5), sex='Female', position='Science Teacher')
# Inserting students (and also users)
student1 = Student.objects.create(username='student1', dob=date(2000, 8, 10), sex='Male', club='Chess Club')
student2 = Student.objects.create(username='student2', dob=date(2001, 6, 15), sex='Female', club='Music Club')
# Inserting courses
course1 = Course.objects.create(name='Mathematics')
course2 = Course.objects.create(name='Science')
# Enrolling students in courses
course1.students.add(student1)
course1.students.add(student2)
course2.students.add(student2)
# Inserting lessons
lesson1 = Lesson.objects.create(course=course1, name='Algebra')
lesson2 = Lesson.objects.create(course=course2, name='Chemistry')
def print_objects():
# Users:
for obj in User.objects.all():
print(obj)
# Teachers: Teacher.objects.all():
# Students: Student.objects.all():
# Courses: Course.objects.all():
# Lessons: Lesson.objects.all():
# Enrollments: Enrollment.objects.all():
if __name__ == '__main__':
# Django setup
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
django.setup()
insert_data() # Inserting data
print_objects() # Printing objects