不使用Django Admin且搭建静态页面网站,启动项目需执行migrate吗?
migrate for a Static Django Site Without Admin? Great question! Let's break this down clearly:
Short answer: No, you don't have to run
migrateif you're building a purely static site that never touches the database and doesn't use Django Admin or any database-dependent built-in features.Why
migrateexists in the first place: Themigratecommand syncs Django model changes to your database. By default, new Django projects include apps likedjango.contrib.auth,django.contrib.sessions, anddjango.contrib.contenttypesinINSTALLED_APPS—these rely on database tables to work. But if you don't need user authentication, session tracking, or any other feature that uses a database, you can skip this step entirely.Important caveat: If you leave those database-dependent apps in your
INSTALLED_APPSbut don't runmigrate, you'll get errors when starting the server. Django will try to access tables that don't exist. So you have two solid options here:- Strip down your
INSTALLED_APPS: Remove all apps that require a database (likeauth,sessions,admin,contenttypes). Keep only what you need for static files, likedjango.contrib.staticfiles, plus your own custom app. This way, you don't need a database at all. - Run
migrateanyway: If you want to keep some of those default apps (even if you don't use Admin), you'll need to runmigrateto create the necessary database tables. For example, if you're using sessions for some edge case (unlikely for a static site), this is necessary.
- Strip down your
Example setup for a static-only site: Your
INSTALLED_APPSmight look like this:INSTALLED_APPS = [ 'django.contrib.staticfiles', # Your custom static site app here, e.g., 'my_static_pages', ]With this setup, you can run
python manage.py runserverdirectly without ever touchingmigrateor setting up a database.
内容的提问来源于stack exchange,提问作者Greg

