티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to change the name of a Django app?
장고 앱 이름 바꾸기
문제 내용
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
폴더, 가져오기 및 모든 참조(템플릿/인덱스)의 이름을 변경하여 장고에서 앱 이름을 변경했습니다. 하지만 이제 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?
이 오류를 디버깅하고 해결하려면 어떻게 해야 합니까? 단서는?
높은 점수를 받은 Solution
Follow these steps to change an app's name in Django:
장고에서 앱 이름을 변경하려면 다음 단계를 수행하십시오.
- Rename the folder which is in your project root
- Change any references to your app in their dependencies, i.e. the app's
views.py
,urls.py
,manage.py
, andsettings.py
files. - Edit the database table
django_content_type
with the following command:UPDATE django_content_type SET app_label='<NewAppName>' WHERE app_label='<OldAppName>'
- 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). - (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. - If your
models.py
's Meta Class hasapp_name
listed, make sure to rename that too (mentioned by @will). - If you've namespaced your
static
ortemplates
folders inside your app, you'll also need to rename those. For example, renameold_app/static/old_app
tonew_app/static/new_app
. - For renaming django
models
, you'll need to changedjango_content_type.name
entry in DB. For postgreSQL, useUPDATE django_content_type SET name='<newModelName>' where name='<oldModelName>' AND app_label='<OldAppName>'
- Update 16Jul2021: Also, the
__pycache__/
folder inside the app must be removed, otherwise you getEOFError: marshal data too short when trying to run the server
. Mentioned by @Serhii Kushchenko
1. 프로젝트 루트에 있는 폴더 이름 바꾸기
2. 앱에 대한 모든 참조(예: 앱의 views.py, urls.py , manage.py 및 settings.py 파일)를 변경합니다.
3. 다음 명령을 사용하여 데이터베이스 테이블 django_content_type을 편집합니다. UPDATE django_content_type SET app_label=''WHERE app_label='<이전 앱 이름>'
4. 또한 모델이 있는 경우 모델 테이블의 이름을 변경해야 합니다. postgres의 경우 ALTER TABLE _modelName RNAME TO _modelName을(를) 사용합니다. mysql도 마찬가지라고 생각합니다(@null_radix에서 언급한 것과 동일).
5. (Django >= 1.7의 경우) 이전 마이그레이션이 다시 실행되지 않도록 django_migrations 테이블 업데이트: UPDATE django_migrations SET app=' 'WHERE app='. 참고:장고 1.8+에 대해 이 단계가 필요한지에 대한 논란이 있습니다. 누군가 확실히 알고 있다면 여기를 업데이트하십시오.
6. models.py의 메타 클래스에 app_name이 나열되어 있으면 이름도 반드시 변경하십시오(@will에서 언급함).
7. 앱 내에서 정적 또는 템플릿 폴더의 네임스페이스를 지정한 경우 해당 폴더의 이름도 변경해야 합니다. 예를 들어 old_app/static/old_app의 이름을 new_app/static/new_app으로 변경합니다.
8. django 모델의 이름을 변경하려면 DB에서 django_content_type.name 항목을 변경해야 합니다. postgre용SQL에서 update django_content_type SET name='' 여기서 name=''과 app_label='을 사용하십시오.<이전 앱 이름>'
9. 업데이트 16Jul2021: 또한 앱 내의 __pycache__/ 폴더를 제거해야 합니다. 그렇지 않으면 서버를 실행하려고 할 때 EOFError: marshal data too short when trying to run the server 를 받습니다. @Serhi Kushchenko가 언급했다.
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).
메타 포인트(virtualenv를 사용하는 경우): 가상 env가 포함된 디렉토리의 이름을 변경하는 경우 env에 절대 경로가 포함된 파일이 여러 개 있을 수 있으며 업데이트도 필요합니다. ImportError: No module named ......와 같은 오류가 발생하는 경우 이것이 범인일지도 모른다. (이것을 제공해 준 @danyamachine 덕분입니다.)
Other references: you might also want to refer to the below links for a more complete picture:
기타 참고 자료: 아래 링크를 참조하여 전체 그림을 확인할 수도 있습니다.
- Renaming an app with Django and South
- How do I migrate a model out of one django app and into a new one?
- How to change the name of a Django app?
- Backwards migration with Django South
- Easiest way to rename a model using Django/South?
- Python code (thanks to A.Raouf) to automate the above steps (Untested code. You have been warned!)
- Python code (thanks to rafaponieman) to automate the above steps (Untested code. You have been warned!)
가장 최근 달린 Solution
In many cases, I believe @allcaps's answer works well.
@allcaps의 대답이 잘 통하는 경우가 많다고 생각합니다.
However, sometimes it is necessary to actually rename an app, e.g. to improve code readability or prevent confusion.
그러나 코드 가독성을 개선하거나 혼동을 방지하기 위해 앱의 이름을 실제로 변경해야 하는 경우가 있다.
Most of the other answers involve either manual database manipulation or tinkering with existing migrations, which I do not like very much.
대부분의 다른 답변은 수동 데이터베이스 조작이나 기존 마이그레이션을 만지작거리는 것을 포함하고 있는데, 저는 이를 별로 좋아하지 않습니다.
As an alternative, I like to create a new app with the desired name, copy everything over, make sure it works, then remove the original app:
또는 원하는 이름으로 새 앱을 만들고 모든 것을 복사하여 작동하는지 확인한 다음 원래 앱을 제거하는 것을 좋아합니다.
- Start a new app with the desired name, and copy all code from the original app into that. Make sure you fix the namespaced stuff, in the newly copied code, to match the new app name.
makemigrations
andmigrate
. Note: if the app has a lot of foreign keys, there will likely be issues with clashing reverse accessors when trying to run the initial migration for the copied app. You have to rename the related_name accessor (or add new ones) on the old app to resolve the clashes.- Create a data migration that copies the relevant data from the original app's tables into the new app's tables, and
migrate
again.
1. 원하는 이름으로 새 앱을 시작하고 원래 앱의 모든 코드를 해당 앱에 복사합니다. 새로 복사한 코드의 네임스페이스 부분을 새 앱 이름과 일치하도록 수정해야 합니다.
2. makemigrations 및 migrate을 수행합니다. 참고: 앱에 외부 키가 많은 경우 복사된 앱에 대해 초기 마이그레이션을 실행할 때 역방향 액세스자가 충돌하는 문제가 발생할 수 있습니다. 충돌을 해결하려면 이전 앱에서 related_name 접근자의 이름을 변경하거나 새 접근자를 추가해야 합니다.
3. 원래 앱의 테이블에서 새 앱의 테이블로 관련 데이터를 복사하는 데이터 마이그레이션을 만든 후 다시 마이그레이션합니다.
At this point, everything still works, because the original app and its data are still in place.
이 시점에서 원래 앱과 해당 데이터가 여전히 제자리에 있기 때문에 모든 것이 여전히 작동합니다.
- Now you can refactor all the dependent code, so it only makes use of the new app. See other answers for examples of what to look out for.
- Once you are certain that everything works, you can remove the original app. This involves another (schema) migration.
4. 이제 모든 종속 코드를 리팩터링할 수 있으므로 새 앱만 사용할 수 있습니다. 주의해야 할 사항에 대한 예는 다른 답변을 참조하십시오.
5. 모든 것이 작동하는지 확인하면 원래 앱을 제거할 수 있습니다. 여기에는 다른(스키마) 마이그레이션이 포함됩니다.
This has the advantage that every step uses the normal Django migration mechanism, without manual database manipulation, and we can track everything in source control. In addition, we keep the original app and its data in place until we are sure everything works.
이것은 모든 단계가 수동 데이터베이스 조작 없이 일반적인 장고 마이그레이션 메커니즘을 사용하고 소스 제어의 모든 것을 추적할 수 있다는 장점이 있다. 또한 모든 것이 제대로 작동하는지 확인할 때까지 원본 앱과 해당 데이터를 제자리에 보관합니다.
출처 : https://stackoverflow.com/questions/8408046/how-to-change-the-name-of-a-django-app
'개발 > 파이썬' 카테고리의 다른 글
파이썬에서 파일 이동시키기 (0) | 2022.12.03 |
---|---|
기존 파일에 내용 추가하기 (0) | 2022.12.03 |
Dictionary에서 아이템(요소) 삭제 (0) | 2022.12.02 |
가장 효율적인 변수 타입 확인 방법 (0) | 2022.12.02 |
값 기준으로 Dictionary 정렬하기 (0) | 2022.12.02 |