What is the purpose of apps.py in Django 1.9?

Django

Django Problem Overview


I just went over the alpha release notes for Django 1.9 and saw that the startapp management command now adds an apps.py file.

What's the purpose of this file? The startapp documentation didn't provide more information.

Django Solutions


Solution 1 - Django

Purpose of apps.py file:

This file is created to help the user include any application configuration for the app. Using this, you can configure some of the attributes of the application.

From Application Configuration documentation:

> Application configuration objects store metadata for an application. > Some attributes can be configured in AppConfig subclasses. Others are > set by Django and read-only.

Example from the docs:

Lets say you’re creating a pluggable app called "Rock ’n’ roll", then to provide a proper name for the admin we can do the following:

In rock_n_roll app, we create a RockNRollConfig AppConfig class.

#rock_n_roll/apps.py
from django.apps import AppConfig

class RockNRollConfig(AppConfig): # Our app config class
    name = 'rock_n_roll'
    verbose_name = "Rock ’n’ roll"

We can make your application load this AppConfig subclass by default by specifying the default_app_config in the rock_n_roll/__init__.py file.

# rock_n_roll/__init__.py    
default_app_config = 'rock_n_roll.apps.RockNRollConfig'

Doing this will cause RockNRollConfig to be used when INSTALLED_APPS just contains 'rock_n_roll'. This allows us to make use of AppConfig features without requiring our users to update their INSTALLED_APPS setting.

Solution 2 - Django

It is the recommended place to put your application configuration. This feature has been here since 1.7, but to promote its use and enable easier configuration, the apps.py file has been added to the default app template.

Solution 3 - Django

apps.py is just an alternate way to update your application related configuration and now when you create new app using below command

python manage.py startapp myapp

you don't need to update the settings.INSTALLED_APPS, above command will by default add below code into the respective myapp/apps.py file

from django.apps import AppConfig


class myappConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'myapp'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLaundroMatView Question on Stackoverflow
Solution 1 - DjangoRahul GuptaView Answer on Stackoverflow
Solution 2 - DjangoknbkView Answer on Stackoverflow
Solution 3 - DjangoShreeyansh JainView Answer on Stackoverflow