Django Dynamic Model Fields
Last Updated :
12 Apr, 2024
In web development, Django is a framework that helps to build awesome websites. One of the main features of Django is dynamic model fields so we will discuss what we mean by dynamic model fields and how to use them in Django. In this article, we will read about the dynamic model fields in Django.
What are Django Dynamic Model Fields?
Dynamic Model fields in Django let you create a model that can change or grow over time when you use dynamic model fields. Dynamic model fields are like a magic box; you can put anything you want and the box adjusts to fit all. For example, you are making a digital library where people can add their types of books. Some might want to add cookbooks, others might add novels and some might even comics so how can you handle all these different types without making a mess? that's all we can handle using Django's dynamic model field.
Django Dynamic Model Fields
Below are the examples of Django dynamic model fields in Python:
Starting the Project Folder
To start the project use this command
django-admin startproject demo
cd demo
To start the app use this command
python manage.py startapp firstt
Now add this app to the ‘settings.py’
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"firstt",
]
File Structure
.png)
Example 1: Generic Relations in Dynamic Model Fields
Generic Relations:
This is like having a magic key that can open any door. With Django's GenericForiegnKey, you can connect one thing to another thing without knowing what those things are in advance.
Django's GenericForiegnKey allows a model to reference any other model instance through the foreign key.
firstt/models.py : To understand the dynamic field models using Generic Relations. I take examples of comments on videos and photos. So I have created a model of photos, videos and comments. In the below code, comment models have a generic relation with photos and videos.
Python3
# models.py
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Comment(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
text = models.TextField()
class Photo(models.Model):
caption = models.CharField(max_length=100)
class Video(models.Model):
title = models.CharField(max_length=100)
firstt/views.py : After creating a model I have created a view for testing generic relations. In views, I have created function generic function and in generic function, views I have added one photo and video then added a comment photo and video after this, I filtered based on content and showed the comments for photos and videos.
Python3
# views.py
from django.shortcuts import render
from .models import Photo, Video, Comment, ContentType
from django.http import HttpResponse
# Create your views here.
def generic_function(request):
photo = Photo.objects.create(caption="Beautiful sunset")
video = Video.objects.create(title="Funny cat video")
comment1 = Comment.objects.create(
content_object=photo, text="Amazing photo!")
comment2 = Comment.objects.create(
content_object=video, text="Hilarious video!")
photo_comments = Comment.objects.filter(
content_type=ContentType.objects.get_for_model(photo), object_id=photo.id)
video_comments = Comment.objects.filter(
content_type=ContentType.objects.get_for_model(video), object_id=video.id)
print("Comments on Photo:")
for comment in photo_comments:
print(comment.text)
print("\nComments on Video:")
for comment in video_comments:
print(comment.text)
return HttpResponse("Generic Function")
firstt/urls.py : After adding the URL of the generic function in urls.py
Python3
# urls.py
from django.urls import path
from .views import generic_function
urlpatterns = [
path('generic/', generic_function, name='generic-url'),
]
After running of local server(http://127.0.0.1:8000/). I have hit this URL (http://127.0.0.1:8000/generic/).
Example 2: JSON Fields (Dynamic Model Fields)
JSONField allows storing JSON data in native JSON format in the database. This field type is particularly useful when you dealing with semi-structure or unstructure data. It is like a big bag where you can all sorts of stuff without worrying about organising it.
Let's say you're developing a platform where users can create custom forms, each with different fields based on their needs. Instead of defining fixed fields for each form, you can use a JSON field to store the form data flexibly. To create this platform we create the first model 'CustomForm'.
firstt/models.py : In the below code, I have created the model CustomForm. In CustomForm Field add name field and form_data field. form_data field is JSONField so in this field, you can add different fields of different users. For testing these fields I have created a view.
Python3
# models.py
from django.db import models
class CustomForm(models.Model):
name = models.CharField(max_length=100)
form_data = models.JSONField()
firstt/views.py : This code dynamically generates a custom form using the provided form_data, creates a CustomForm object with this data, and then returns the form data as an HTTP response
Python3
# views.py
def Json_Field(request):
# Create a custom form
form_data = {
"fields": [
{"name": "name", "type": "text", "label": "Your Name", "required": True},
{"name": "email", "type": "email",
"label": "Your Email", "required": True},
{"name": "message", "type": "textarea",
"label": "Your Message", "required": False}
]
}
custom_form = CustomForm.objects.create(
name="Contact Form", form_data=form_data)
# Retrieve the custom form data
print("Custom Form Data:")
print(custom_form.form_data)
return HttpResponse(f"{custom_form.form_data}")
firstt/urls.py : In this example, I have added data from three persons from different fields.
Add Json_Field views in URLs.
Python3
#urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('generic/', generic_function, name='generic-url'),
path('json/', Json_Field, name='json-url'),
]
admin.py : I have register all models in admin portal.
Python3
# admin.py
from django.contrib import admin
from .models import Comment, Photo, Video, CustomForm
# Register your models here.
admin.site.register(Comment)
admin.site.register(Photo)
admin.site.register(Video)
admin.site.register(CustomForm)
After running of local server(http://127.0.0.1:8000/). I have hit this URL (http://127.0.0.1:8000/json/). In above all example code we need to make migration on code for those follow the below steps, and run in terminal below command.
Deployment of the Project
Run these commands to apply the migrations:
python3 manage.py makemigrations
python3 manage.py migrate
Run the server with the help of following command:
python3 manage.py runserver
Output
Similar Reads
DurationField - Django Models
DurationField is a field for storing periods of time - modeled in Python by timedelta. When used on PostgreSQL, the data type used is an interval and on Oracle the data type is INTERVAL DAY(9) TO SECOND(6). Otherwise, a bigint of microseconds is used. DurationField basically stores a duration, the d
4 min read
EmailField - Django Models
EmailField is a CharField that checks the value for a valid email address using EmailValidator. EmailValidator validates a email through predefined regex which checks '@' and a '.' defined after it. One can change the regex by exploring options from EmailValidator itself. Syntax field_name = models.
4 min read
FileField - Django Models
FileField is a file-upload field. Before uploading files, one needs to specify a lot of settings so that file is securely saved and can be retrieved in a convenient manner. The default form widget for this field is a ClearableFileInput. Syntax field_name = models.FileField(upload_to=None, max_length
6 min read
FloatField - Django Models
FloatField is a floating-point number represented in Python by a float instance. This field is generally used to store huge floating point numbers in the database. The default form widget for this field is a NumberInput when localize is False or TextInput otherwise. Syntax: field_name = models.Float
4 min read
ImageField - Django Models
ImageField is a specialized version of Django's FileField designed to handle image uploads. It restricts uploads to image formats and provides additional attributes for storing image dimensions.Default form widget: ClearableFileInputRequires: Pillow library for image processingInstall Pillow with: p
3 min read
IntegerField - Django Models
IntegerField is a integer number represented in Python by a int instance. This field is generally used to store integer numbers in the database. The default form widget for this field is a NumberInput when localize is False or TextInput otherwise. It supports values from -2147483648 to 2147483647 ar
4 min read
FilePathField - Django Models
FilePathField is a CharField whose choices are limited to the filenames in a certain directory on the filesystem. FilePathField instances are created in your database as varchar columns with a default max length of 100 characters.Syntax:field_name = models.FilePathField(path=None, match=None, recurs
5 min read
GenericIPAddressField - Django Models
GenericIPAddressField is a field which stores an IPv4 or IPv6 address, in string format (e.g. 192.0.2.30 or 2a02:42fe::4). The default form widget for this field is a TextInput. The IPv6 address normalization follows RFC 4291#section-2.2 section 2.2, including using the IPv4 format suggested in para
4 min read
EmailField - Django Forms
EmailField in Django Forms is a string field, for input of Emails. It is used for taking text inputs from the user. The default widget for this input is EmailInput. It uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided. Otherwise, all inputs are valid. EmailFiel
5 min read
DurationField - Django forms
DurationField in Django Forms is used for input of particular durations for example from 12 am to 1 pm. The default widget for this input is TextInput. It Normalizes to: A Python datetime.date object. It validates that the given value is a string which can be converted into a timedelta. DurationFiel
5 min read