IT박스

Django 앱의 이름을 변경하는 방법은 무엇입니까?

itboxs 2020. 7. 4. 11:17
반응형

Django 앱의 이름을 변경하는 방법은 무엇입니까?


Django에서 폴더 이름, 가져 오기 및 모든 참조 (템플릿 / 색인)의 이름을 변경하여 앱 이름을 변경했습니다. 그러나 지금 실행하려고하면이 오류가 발생합니다.python manage.py runserver

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

이 오류를 어떻게 디버깅하고 해결할 수 있습니까? 단서가 있습니까?


Django에서 앱 이름을 변경하려면 다음 단계를 따르십시오.

  1. 프로젝트 루트에있는 폴더의 이름을 바꾸십시오
  2. 자신의 의존성에 응용 프로그램에 대한 참조를 변경 응용 프로그램의 즉 views.py, urls.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. 앱 내부 static또는 templates폴더에 네임 스페이스를 지정한 경우 이름을 바꿔야합니다. 예를 들어로 이름 old_app/static/old_app바꿉니다 new_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>'

메타 포인트 (virtuenv를 사용하는 경우) : virtualenv 가 포함 된 디렉토리의 이름을 바꾸는 경우 env에 절대 경로가 포함 된 여러 파일이있을 수 있으며 업데이트해야합니다. 이와 같은 오류가 발생 ImportError: No module named ...하면 범인 일 수 있습니다. (@danyamachine에게 감사드립니다).

다른 참조 : 더 완벽한 그림을 보려면 아래 링크를 참조하십시오

  1. Django와 South로 앱 이름 바꾸기
  2. 하나의 장고 앱에서 새 모델로 모델을 어떻게 마이그레이션합니까?
  3. Django 앱의 이름을 변경하는 방법은 무엇입니까?
  4. Django South를 통한 이전 마이그레이션
  5. Django / South를 사용하여 모델의 이름을 바꾸는 가장 쉬운 방법은 무엇입니까?
  6. 위의 단계를 자동화하는 Python 코드 ( A.Raouf 덕분에 ) (테스트되지 않은 코드. 경고되었습니다!)
  7. 위의 단계를 자동화하는 Python 코드 ( rafaponieman 덕분에 ) (테스트되지 않은 코드. 경고되었습니다!)

Django 1.7의 새로운 기능은 구성을 저장하고 내부 검사를 제공하는 앱 레지스트리입니다. 이 기계를 사용하면 몇 가지 앱 속성을 변경할 수 있습니다.

내가 만들고 싶은 요점은 앱 이름을 바꿀 필요가 없다는 것입니다. 앱 구성을 사용하면 충돌하는 앱을 해결할 수 있습니다. 또한 앱에 친숙한 이름이 필요한 경우 갈 길도 있습니다.

예를 들어 설문 조사 앱의 이름을 '사용자의 피드백'으로 지정하고 싶습니다. 다음과 같이 진행됩니다.

디렉토리에 apps.py파일을 작성하십시오 polls.

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/en/1.7/ref/applications/


PyCharm을 사용 중이고 이름을 바꾼 후 프로젝트 작동이 중지 된 경우 :

  1. 프로젝트 이름을 포함하므로 실행 / 디버그 구성을 편집하고 환경 변수 DJANGO_SETTINGS_MODULE을 변경하십시오.
  2. 설정 / 언어 및 프레임 워크 / 장고로 이동하여 설정 파일 위치를 업데이트하십시오.

재미있는 문제! 곧 많은 앱의 이름을 바꿔야하므로 드라 이런을했습니다.

이 방법을 사용하면 이름을 바꾸는 앱에서 작업하는 다른 개발자의 방해를 최소화하기 위해 원자 단계로 진행할 수 있습니다.

예제 코드 예제는이 답변의 맨 아래에있는 링크를 참조하십시오.

  1. 이동을 위해 기존 코드를 준비하십시오 .
    • 앱 구성을 만듭니다 ( 기본값 namelabel기본값으로 설정 ).
    • 에 앱 구성을 추가하십시오 INSTALLED_APPS.
    • 모든 모델 db_table에서 현재 값 으로 명시 적으로 설정 하십시오.
    • 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.


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.

참고URL : https://stackoverflow.com/questions/8408046/how-to-change-the-name-of-a-django-app

반응형