Django Admin models validation using forms

Posted 3 years, 12 months ago
Views 449
1 min read
0 reactions

In this section, we are going to discuss about Django admin validation.

Lets assume, we have a project & app in place,

Just for sake, assume we have Post model in our app with below stuff,

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()

    def __str__(self):
       return self.content

Now, we can create the form with the below content,

from django import forms

from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Status
        fields = [

    def clean(self, *args, **kwargs):
        data = self.cleaned_data
        content = data.get('content', None)
        title= data.get('title', None)
        if content == "":
            content = None
        if title== "":
            title= None

        if content is None and titleis None:
            raise forms.ValidationError('Content or title is required.')
        return super().clean(*args, **kwargs)

Now, its time to register our model into file,

from django.contrib import admin

from .forms import PostForm
from .models import Post

class PostAdmin(admin.ModelAdmin):
    form = PostForm, PostAdmin)

As you noticed, we have used our form object in to our admin file.

Thats it !!!. Now, if we visit the admin page & validate this. It should work as expected. Here I am not posting any screenshot of the output. If you would like to know that, let me know in comment section, I will update it accordingly.

Happy Coding !!!

0 reactions


Posted 3 years, 11 months ago


I am new here

Joined on April 19, 2020

Latest Videos