Open In App

How Do we Reference a Django Settings Variable in My models.py?

Last Updated : 09 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

One common requirement in Django projects is accessing the settings variables defined in the settings.py file in different apps. We can use the settings variables anywhere in our project. We only need to add an import statement 'from django.conf import settings' and refer to the variable using the settings.<Variable Name>. In this article, we will show you how to reference a Django settings variable in your models.py file.

Defining Settings Variables in settings.py

In your settings.py file, add a variable of your choice and assign a value you want to use in your models.py file.

For example, let's say, you want to set a default value for a model field defined in the settings.py file.

settings.py

Python
# ...

MY_DEFAULT_VALUE = 'This is a custom setting value'

# ...

Models.py

Now, in the models.py file of your application, import settings from django.conf.

In this example, the setting_value field in MyModel is set to the value of MY_DEFAULT_VALUE from the settings.py file.

Python
# myapp/models.py

from django.db import models
from django.conf import settings

class MyModel(models.Model):
    name = models.CharField(max_length=100)
    setting_value = models.CharField(max_length=255, default=settings.MY_CUSTOM_SETTING)
    
    def __str__(self):
        return self.name

Register the Model in Admin

Let's register the MyModel in the admin.py file and to see your changes, you can go to the admin panel and create some instances.

admin.py

Python
from django.contrib import admin
from .models import MyModel

admin.site.register(MyModel)

Making Migrations

Run the following commands to create and apply migrations:

python manage.py makemigrations
python manage.py migrate

Creating a Superuser

Create a superuser to access the Django admin interface in you don't have one:

python manage.py createsuperuser

Run the Development Server

python manage.py runserver

Visit http://127.0.0.1:8000/admin in your browser, log in with the superuser credentials, and you will see the MyModel in the admin interface. And yes, we have successfully used the setting variables in the models.py file.

1



Next Article
Article Tags :
Practice Tags :

Similar Reads