You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中编写Python脚本添加数据库行?执行遇应用未加载错误

Fixing Django's "Apps aren't loaded yet" Error When Running a Standalone Script

Hey there! That AppRegistryNotReady error pops up because your standalone Python script isn't initializing Django's application environment first. Django needs to load all its app configurations, settings, and database connections before you can interact with models—let's fix this with a few solid, practical options.

Option 1: Manually Initialize Django in Your Script

Perfect for one-off scripts. You just need to set up Django's environment before importing any models:

import os
import django

# Tell Django where your project's settings file lives
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
# Initialize Django's app registry and core systems
django.setup()

# Now you can safely import and use your models
from mysite.models import School

# Your original code works now!
school1 = School(name='Oxford school', address='Shole St.33', email='ox-scholl@gmail.com', phone_number='3445348910')
school1.save()
print("Successfully added the school to the database!")

Quick breakdown:

  • os.environ.setdefault(...): This points Django to your project's settings module (replace mysite.settings if your settings path is different).
  • django.setup(): This triggers Django to load all installed apps, connect to the database, and get everything ready for model operations. This line must run before importing any models.

Option 2: Use Django's Built-in Shell (Quickest for Testing)

If you just need to run this code once for testing, skip writing a standalone script entirely and use Django's shell:

  1. Open your terminal, navigate to your Django project root (where manage.py lives).
  2. Run this command:
    python manage.py shell
    
  3. Once the shell loads, paste your original code directly:
    from mysite.models import School
    school1 = School(name='Oxford school', address='Shole St.33', email='ox-scholl@gmail.com', phone_number='3445348910')
    school1.save()
    

The shell automatically initializes Django's environment, so you won't hit the app registry error at all.

Option 3: Create a Custom Django Management Command (Best for Reusable Scripts)

If you plan to run this code multiple times or want to follow Django's best practices, build a custom management command:

  1. In your mysite app, create these directories (if they don't exist):
    mysite/
      management/
        commands/
          __init__.py
          add_school.py
    
  2. Paste this code into add_school.py:
    from django.core.management.base import BaseCommand
    from mysite.models import School
    
    class Command(BaseCommand):
        help = 'Adds a new school entry to the database'
    
        def handle(self, *args, **options):
            # Create and save the school
            school1 = School(name='Oxford school', address='Shole St.33', email='ox-scholl@gmail.com', phone_number='3445348910')
            school1.save()
            # Print a formatted success message
            self.stdout.write(self.style.SUCCESS(f"Successfully added school: {school1.name}"))
    
  3. Run the command from your project root:
    python manage.py add_school
    

This method integrates seamlessly with Django's ecosystem—you can even add command-line arguments later if you need to customize the school data dynamically.


内容的提问来源于stack exchange,提问作者Pavel Silber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:29:05