Django Admin models validation using forms

||
Posted 2 years ago
||
Views 181
||
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 = [
            'title',
            'content'
        ]

    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 admin.py file,

from django.contrib import admin

from .forms import PostForm
from .models import Post


class PostAdmin(admin.ModelAdmin):
    
    form = PostForm



admin.site.register(Post, 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

Discussion

oyerohabib
Posted 1 year, 11 months ago

Hello

I am new here



Joined on April 19, 2020


Latest Videos


Wanna Post Ad?
Reach a large group of audience by posting an ad about your business here. For more details
Drop us a Message