如何更改Django应用的名称?

问题:如何更改Django应用的名称?

我通过重命名应用程序的文件夹,导入及其所有引用(模板/索引)来更改了Django中应用程序的名称。但是现在当我尝试运行时出现此错误python manage.py runserver

Error: Could not import settings 'nameofmynewapp.settings' (Is it on sys.path?): No module named settings

如何调试和解决此错误?有什么线索吗?

I have changed the name of an app in Django by renaming its folder, imports and all its references (templates/indexes). But now I get this error when I try to run python manage.py runserver

Error: Could not import settings 'nameofmynewapp.settings' (Is it on sys.path?): No module named settings

How can I debug and solve this error? Any clues?


回答 0

请按照以下步骤在Django中更改应用的名称:

  1. 重命名项目根目录中的文件夹
  2. 更改为您的应用程序的任何引用他们的依赖关系,即应用程序的views.pyurls.py“manage.py”,和settings.py文件。
  3. django_content_type使用以下命令编辑数据库表:UPDATE django_content_type SET app_label='<NewAppName>' WHERE app_label='<OldAppName>'
  4. 另外,如果您有模型,则必须重命名模型表。供postgres使用ALTER TABLE <oldAppName>_modelName RENAME TO <newAppName>_modelName。对于MySQL我也认为它是相同的(如@null_radix所提到的)
  5. (对于Django> = 1.7),更新django_migrations表以避免重新运行以前的迁移:UPDATE django_migrations SET app='<NewAppName>' WHERE app='<OldAppName>'注意:对于Django 1.8+是否需要执行此步骤,存在一些参数(在注释中)。如果有人知道,请在这里更新。
  6. 如果您models.py的的元类已app_name列出,请确保也将其重命名(由@will提及)。
  7. 如果您已在应用程序中为statictemplates文件夹命名空间,则还需要重命名它们。例如,重命名old_app/static/old_appnew_app/static/new_app
  8. 要重命名django models,您需要更改django_content_type.nameDB中的条目。对于PostgreSQL使用UPDATE django_content_type SET name='<newModelName>' where name='<oldModelName>' AND app_label='<OldAppName>'

元点(如果使用virtualenv):值得注意的是,如果要重命名包含virtualenv的目录,则env中可能有几个文件包含绝对路径,并且也需要更新。如果您遇到诸如此类的错误,ImportError: No module named ...可能是罪魁祸首。(感谢@danyamachine提供此功能)。

其他参考:您可能还想参考以下链接以获得更完整的图片

  1. 使用Django和South重命名应用程序
  2. 如何将模型从一个django应用程序迁移到新的模型中?
  3. 如何更改Django应用的名称?
  4. 使用Django South向后迁移
  5. 使用Django / South重命名模型的最简单方法?
  6. Python代码(感谢A.Raouf)可以自动完成上述步骤(未经测试的代码。已警告您!)
  7. Python代码(感谢rafaponieman)可以自动完成上述步骤(未经测试的代码。已警告您!)

Follow these steps to change an app’s name in Django:

  1. Rename the folder which is in your project root
  2. Change any references to your app in their dependencies, i.e. the app’s views.py, urls.py , ‘manage.py’ , and settings.py files.
  3. Edit the database table django_content_type with the following command: UPDATE django_content_type SET app_label='<NewAppName>' WHERE app_label='<OldAppName>'
  4. Also if you have models, you will have to rename the model tables. For postgres use ALTER TABLE <oldAppName>_modelName RENAME TO <newAppName>_modelName. For mysql too I think it is the same (as mentioned by @null_radix)
  5. (For Django >= 1.7) Update the django_migrations table to avoid having your previous migrations re-run: UPDATE django_migrations SET app='<NewAppName>' WHERE app='<OldAppName>'. Note: there is some debate (in comments) if this step is required for Django 1.8+; If someone knows for sure please update here.
  6. If your models.py ‘s Meta Class has app_name listed, make sure to rename that too (mentioned by @will).
  7. If you’ve namespaced your static or templates folders inside your app, you’ll also need to rename those. For example, rename old_app/static/old_app to new_app/static/new_app.
  8. For renaming django models, you’ll need to change django_content_type.name entry in DB. For postgreSQL use UPDATE django_content_type SET name='<newModelName>' where name='<oldModelName>' AND app_label='<OldAppName>'

Meta point (If using virtualenv): Worth noting, if you are renaming the directory that contains your virtualenv, there will likely be several files in your env that contain an absolute path and will also need to be updated. If you are getting errors such as ImportError: No module named ... this might be the culprit. (thanks to @danyamachine for providing this).

Other references: you might also want to refer the below links for a more complete picture

  1. Renaming an app with Django and South
  2. How do I migrate a model out of one django app and into a new one?
  3. How to change the name of a Django app?
  4. Backwards migration with Django South
  5. Easiest way to rename a model using Django/South?
  6. Python code (thanks to A.Raouf) to automate the above steps (Untested code. You have been warned!)
  7. Python code (thanks to rafaponieman) to automate the above steps (Untested code. You have been warned!)

回答 1

Django 1.7中的新功能是一个应用程序注册表,它存储配置并提供自省功能。通过这种机制,您可以更改几个应用程序属性。

我要提出的主要观点是,重命名应用程序并非总是必要的:通过应用程序配置,可以解决冲突的应用程序。但是,如果您的应用需要友好的命名方式,这也是可行的方法。

例如,我想将民意调查应用命名为“用户反馈”。它是这样的:

apps.pypolls目录中创建一个文件:

from django.apps import AppConfig

class PollsConfig(AppConfig):
    name = 'polls'
    verbose_name = "Feedback from users"

将默认应用配置添加到您的polls/__init__.py

default_app_config = 'polls.apps.PollsConfig'

有关更多应用程序配置:https : //docs.djangoproject.com/zh-CN/1.7/ref/applications/

New in Django 1.7 is a app registry that stores configuration and provides introspection. This machinery let’s you change several app attributes.

The main point I want to make is that renaming an app isn’t always necessary: With app configuration it is possible to resolve conflicting apps. But also the way to go if your app needs friendly naming.

As an example I want to name my polls app ‘Feedback from users’. It goes like this:

Create a apps.py file in the polls directory:

from django.apps import AppConfig

class PollsConfig(AppConfig):
    name = 'polls'
    verbose_name = "Feedback from users"

Add the default app config to your polls/__init__.py:

default_app_config = 'polls.apps.PollsConfig'

For more app configuration: https://docs.djangoproject.com/en/1.7/ref/applications/


回答 2

好玩的问题!我很快将不得不重命名许多应用程序,所以我做了一次试运行。

此方法允许逐步执行进度,以最大程度地减少对正在重命名的应用程序上工作的其他开发人员的干扰。

有关有效的示例代码,请参见此答案底部的链接。

  1. 准备移动的现有代码
    • 创建一个应用程序配置(设置namelabel为默认值)。
    • 将应用程序配置添加到中INSTALLED_APPS
    • 在所有模型上,将其显式设置db_table为当前值。
    • 医生迁移,因此db_table“总是”被明确定义。
    • 确保不需要迁移(请检查上一步)。
  2. 更改应用标签

    • label在应用程序配置中设置为新的应用程序名称。
    • 更新迁移和外键以引用新的应用标签。
    • 更新基于类的通用视图的模板(默认路径为<app_label>/<model_name>_<suffix>.html
    • 运行原始SQL来修复迁移和content_types应用(不幸的是,某些原始SQL是不可避免的)。您不能在迁移中运行它。

      UPDATE django_migrations
         SET app = 'catalogue'
       WHERE app = 'shop';
      
      UPDATE django_content_type
         SET app_label = 'catalogue'
       WHERE app_label = 'shop';
      
    • 确保不需要迁移(请检查上一步)。

  3. 重命名表
    • 删除“ custom” db_table
    • 运行,makemigrations以便django可以将表重命名为“默认”。
  4. 移动文件
    • 重命名模块目录。
    • 修复导入。
    • 更新应用程序的配置name
    • 更新INSTALLED_APPS引用应用程序配置的位置。
  5. 整理
    • 如果不再需要自定义应用程序配置,请删除它。
    • 如果应用程序配置消失了,别忘了也将其从中删除INSTALLED_APPS

示例解决方案:我创建了app-rename-example这个示例项目,您可以在其中看到如何重命名应用,一次提交一次。

该示例使用Python 2.7和Django 1.8,但我相信相同的过程至少可以在Python 3.6和Django 2.1上运行。

Fun problem! I’m going to have to rename a lot of apps soon, so I did a dry run.

This method allows progress to be made in atomic steps, to minimise disruption for other developers working on the app you’re renaming.

See the link at the bottom of this answer for working example code.

  1. Prepare existing code for the move:
    • Create an app config (set name and label to defaults).
    • Add the app config to INSTALLED_APPS.
    • On all models, explicitly set db_table to the current value.
    • Doctor migrations so that db_table was “always” explicitly defined.
    • Ensure no migrations are required (checks previous step).
  2. Change the app label:

    • Set label in app config to new app name.
    • Update migrations and foreign keys to reference new app label.
    • Update templates for generic class-based views (the default path is <app_label>/<model_name>_<suffix>.html)
    • Run raw SQL to fix migrations and content_types app (unfortunately, some raw SQL is unavoidable). You can not run this in a migration.

      UPDATE django_migrations
         SET app = 'catalogue'
       WHERE app = 'shop';
      
      UPDATE django_content_type
         SET app_label = 'catalogue'
       WHERE app_label = 'shop';
      
    • Ensure no migrations are required (checks previous step).

  3. Rename the tables:
    • Remove “custom” db_table.
    • Run makemigrations so django can rename the table “to the default”.
  4. Move the files:
    • Rename module directory.
    • Fix imports.
    • Update app config’s name.
    • Update where INSTALLED_APPS references the app config.
  5. Tidy up:
    • Remove custom app config if it’s no longer required.
    • If app config gone, don’t forget to also remove it from INSTALLED_APPS.

Example solution: I’ve created app-rename-example, an example project where you can see how I renamed an app, one commit at a time.

The example uses Python 2.7 and Django 1.8, but I’m confident the same process will work on at least Python 3.6 and Django 2.1.


回答 3

如果您使用的是PyCharm,并且项目在重命名后停止工作:

  1. 编辑运行/调试配置并更改环境变量DJANGO_SETTINGS_MODULE,因为它包含您的项目名称。
  2. 转到设置/语言和框架/ Django并更新设置文件位置。

In case you are using PyCharm and project stops working after rename:

  1. Edit Run/Debug configuration and change environment variable DJANGO_SETTINGS_MODULE, since it includes your project name.
  2. Go to Settings / Languages & Frameworks / Django and update the settings file location.

回答 4

重新迁移清洁板的方法。

如果其他应用程序没有要重命名的应用程序中的外键模型,则可以轻松完成此操作。检查并确保其迁移文件未列出此迁移中的任何迁移。

  1. 备份数据库。转储所有具有a)数据+架构的表,以获取可能的循环依赖关系,以及b)仅重新加载数据。
  2. 运行测试。
  3. 将所有代码检入VCS。
  4. 删除要重命名的应用程序的数据库表。
  5. 删除权限: delete from auth_permission where content_type_id in (select id from django_content_type where app_label = '<OldAppName>')
  6. 删除内容类型: delete from django_content_type where app_label = '<OldAppName>'
  7. 重命名应用程序的文件夹。
  8. 更改为您的应用程序的任何引用他们的依赖关系,即应用程序的views.pyurls.py“manage.py”,和settings.py文件。
  9. 删除迁移: delete from django_migrations where app = '<OldAppName>'
  10. 如果您models.py的的元类已app_name列出,请确保也将其重命名(由@will提及)。
  11. 如果您已在应用程序中为statictemplates文件夹命名空间,则还需要重命名它们。例如,重命名old_app/static/old_appnew_app/static/new_app
  12. 如果您在apps.py中定义了应用程序配置;重命名它们,然后在设置中重命名它们的引用。INSTALLED_APPS
  13. 删除迁移文件。
  14. 重新进行迁移,然后进行迁移。
  15. 从备份加载表数据。

Re-migrate approach for a cleaner plate.

This can painlessly be done IF other apps do not foreign key models from the app to be renamed. Check and make sure their migration files don’t list any migrations from this one.

  1. Backup your database. Dump all tables with a) data + schema for possible circular dependencies, and b) just data for reloading.
  2. Run your tests.
  3. Check all code into VCS.
  4. Delete the database tables of the app to be renamed.
  5. Delete the permissions: delete from auth_permission where content_type_id in (select id from django_content_type where app_label = '<OldAppName>')
  6. Delete content types: delete from django_content_type where app_label = '<OldAppName>'
  7. Rename the folder of the app.
  8. Change any references to your app in their dependencies, i.e. the app’s views.py, urls.py , ‘manage.py’ , and settings.py files.
  9. Delete migrations: delete from django_migrations where app = '<OldAppName>'
  10. If your models.py ‘s Meta Class has app_name listed, make sure to rename that too (mentioned by @will).
  11. If you’ve namespaced your static or templates folders inside your app, you’ll also need to rename those. For example, rename old_app/static/old_app to new_app/static/new_app.
  12. If you defined app config in apps.py; rename those, and rename their references in settings.INSTALLED_APPS
  13. Delete migration files.
  14. Re-make migrations, and migrate.
  15. Load your table data from backups.

回答 5

如果您使用Pycharm,则通过重构所有项目文件(Shift+ F6默认值)非常容易重命名应用程序。
但是,请确保删除__pycache__项目目录及其子目录中的文件夹。也要小心,因为它也会重命名注释,您可以在重构预览窗口中将其排除在注释之外,它会向您显示。
而且,您还必须重命名您已重apps.py命名的应用程序中的OldNameConfig(AppConfig):。

如果您不想丢失数据库的数据,则必须使用上述查询中的数据库查询手动进行操作。

If you use Pycharm, renaming an app is very easy with refactoring(Shift+F6 default) for all project files.
But make sure you delete the __pycache__ folders in the project directory & its sub-directories. Also be careful as it also renames comments too which you can exclude in the refactor preview window it will show you.
And you’ll have to rename OldNameConfig(AppConfig): in apps.py of your renamed app in addition.

If you do not want to lose data of your database, you’ll have to manually do it with query in database like the aforementioned answer.


回答 6

为什么不只使用选项“查找并替换”。(每个代码编辑器都有)吗?

例如,Visual Studio代码(在“编辑”选项下):

您只需键入旧名称和新名称,然后单击一下即可替换项目中的所有内容。

注意:这仅重命名文件内容,而不重命名文件和文件夹名称。不要忘记重命名文件夹,例如。templates/my_app_name/重命名为templates/my_app_new_name/

Why not just use the option Find and Replace. (every code editor has it)?

For example Visual Studio Code (under Edit option):

You just type in old name and new name and replace everyhting in the project with one click.

NOTE: This renames only file content, NOT file and folder names. Do not forget renaming folders, eg. templates/my_app_name/ rename it to templates/my_app_new_name/