Basic Example of a Custom Django Form
Tags: django, djangoforms, webdev, beginners
Published: 2023-04-15 16:49:27

Django is a popular Python web framework that offers a lot of flexibility and customization options. One of the most powerful features of Django is its ability to create custom form classes that can be used to manipulate data in your models. 

In this article, we'll show you how to create a custom form class for a Django model field. 

We'll be writing additional how-tos for more complicated use cases that we've come across for our automotive platform. For instance when handling addresses in our analytics platform (see [Lonestar Chervolet](https://www.topmarq.com/dealers/reviews/lone-star-chevrolet/) ), things become much more complicated as a single field in the form actually consists of many components like city, state, lat/lng, etc. But as always, you have to start with the basics! 


## Step 1: Define the model

Before you can create a custom form class for a model field, you need to define the model itself. Let's say, for example, that we want to create a custom form class for a field called "age" in a "Person" model. Here's what the model might look like:

```
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=255)
    age = models.IntegerField()
```

## Step 2: Create the form class

Now that you have your model defined, you can create the custom form class for the "age" field. To do this, you'll need to create a new Python file in your Django app and define a new class that inherits from the base form class (in this case, forms.ModelForm).

```
from django import forms
from .models import Person

class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = ['age']
```

In this example, we've defined a new form class called "PersonForm" that only includes the "age" field from our Person model.

## Step 3: Customize the form class

Now that you have a basic form class, you can customize it to fit your needs. For example, you might want to add validation to the form to make sure that the user enters a valid age. You can do this by adding a new method to the PersonForm class:


```
class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = ['age']

    def clean_age(self):
        age = self.cleaned_data['age']
        if age < 0 or age > 120:
            raise forms.ValidationError('Invalid age')
        return age
```

In this example, we've added a new method called clean_age() that checks to make sure that the age entered by the user is between 0 and 120. If the age is outside of this range, we raise a validation error.


## Step 4: Use the custom form in your views

Finally, you can use your custom form class in your views. Here's an example of how you might use the PersonForm class to create a new person record in your database:

```
from django.shortcuts import render
from .forms import PersonForm

def create_person(request):
    if request.method == 'POST':
        form = PersonForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'success.html')
    else:
        form = PersonForm()
    return render(request, 'create_person.html', {'form': form})
```

In this example, we've created a new view called "create_person" that uses the PersonForm class to create a new person record in the database. When the user submits the form, we validate it using the is_valid() method. If the form is valid, we save the record and display a success message. If the form is not valid, we display an error message and allow the user to correct their input.

## Conclusion

In this article, we've shown you how to create a custom form class for a Django model field. By defining your own form classes, you can add validation, custom widgets, and other features to your Django forms. This gives you a lot of flexibility and customization options when working with Django.