Skip to content

How to create custom model fields in Django

advanced django models tips & tricks

A custom model field is a way to extend the functionality of a Django model by adding a new field type that is not provided by the built-in fields. For example, you might want to create a custom field that stores a password in a hashed format for security purposes. Custom model fields are implemented as classes that inherit from the django.db.models.Field class.

How to create a custom model field with the example?

How to custom model manager django?

To create a custom model field, you will need to define the following methods in your custom field class:

  • db_type(self, connection): Returns the database column data type for the field.
  • to_python(self, value): Converts the value from the database to a Python object.
  • get_prep_value(self, value): Converts the Python object to a value that can be inserted into the database.

Here is a django custom model field example of a simple custom model field that stores an email address in a hashed format:

import hashlib
from django.db import models

class HashedEmailField(models.Field):
    def db_type(self, connection):
        return 'varchar(255)'

    def to_python(self, value):
        return value

    def get_prep_value(self, value):
        return hashlib.sha1(value.encode('utf-8')).hexdigest()

Once you have defined your custom django model field, you can use it in your model like any other field:

class Person(models.Model):
    email = HashedEmailField()
    # other fields ...

You can also use the django model form custom field as bellow sample:

class PersonForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('email')
Another Example: PhoneNumberField

Custom field: A PhoneNumberField that automatically formats phone numbers as they are stored in the database.

import re

class PhoneNumberField(models.CharField):
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 20
        super().__init__(*args, **kwargs)

    #save the formatted number
    def get_prep_value(self, value):
        value = re.sub(r'[^0-9]', '', str(value))
        return '+{}-{}-{}'.format(value[:1], value[1:4], value[4:]

As usual, the fields automatically add to the django model admin custom field.

The Short Note:

In short, custom fields and managers in Django offer a powerful way to take control of your models, making them as unique as your project’s requirements. These fields allow you to build a bridge between your data and its representation, giving you the power to shape it to your needs. Comments below if you have any doubts.

Related tutorial: 25 Git commands to speed up your developer life

Leave a Reply

Your email address will not be published. Required fields are marked *