Aj1
Aj1

Reputation: 973

Django app_label is wrong on models

I have a Django DRF application. Here is my project structure.

myproject/
    myproject/
    apps/
        myApp1/
            __init__.py
            apps.py
            admin.py
            models.py
            urls.py
            views.py
        myApp2/
        __init__.py
    static/
    manage.py

and myINSTALLED_APPS contains:

INSTALLED_APPS = [
    'apps.myApp1.apps.AppOneConfig',
    'apps.myApp2.apps.AppTwoConfig',
]

When I went to ./manage.py shell_plus and run:

SomeModel._meta.label

I see myApp1 or myApp2 instead of apps.myApp1 && apps.myApp2. And even in migrations Models are referred as myApp1.Model or myApp2.Model not as apps.myApp1.Model or apps.myApp2.Model

Also, specified AppConfig.

from django.apps import AppConfig


class AppOneConfig(AppConfig):
    name = 'apps.myApp1'
    verbose_name = 'My App One'


Is that expected ? I am pretty new to Django. Can anyone suggest what the mistake was?

Upvotes: 1

Views: 960

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476719

Is that expected?

Yes, that is expected. By default, the app label uses the last part of the "python path". You can change it by specifying this in the AppConfig [Django-doc]. It is the .label attribute [Django-doc] of this AppConfig that determines the app label, and:

(…) It defaults to the last component of name. It should be a valid Python identifier. (…)

Now the .name attribute [Django-doc], and this is:

Full Python path to the application, e.g. 'django.contrib.admin'.

You can specify this by first specifying the AppConfig in the __init__.py file of your myApp1 directory:

# apps/myApp/__init__.py

default_app_config = 'apps.myApp.apps.App1Config'

then you make a file apps.py in the myApp1 directory, and write:

# apps/myApp/apps.py

from django.apps import AppConfig

class App1Config(AppConfig):
    label = 'apps_myapp1'

Note: normally directories use slug_case, so I think it might be better to rename your myApp1 to myapp1 or my_app1.

EDIT: You thus need to set the label attribute of your AppOneConfig to:

class AppOneConfig(AppConfig):
    name = 'apps.myApp1'
    label = 'apps_myapp1'
    verbose_name = 'My App One'

Upvotes: 2

Related Questions