---
title: Validating Form Input With Django
description: Let’s say I’m making a blogging web application using Python and the web framework, Django. I want users to be able to publish “Posts” on my blogging website.
---

Visit our partner [Nestria](https://nestria.org?utm_source=byteacademy&utm_medium=menu-referral)

[![byte_academy_logo](https://www.byteacademy.co/hs-fs/hubfs/BYTE%20logo%20files/byte_academy_logo.png?width=2550&height=3300&name=byte_academy_logo.png) ![byte_academy_logo](https://www.byteacademy.co/hs-fs/hubfs/BYTE%20logo%20files/byte_academy_logo.png?width=2550&height=3300&name=byte_academy_logo.png)](https://www.byteacademy.co)

- Programs 
    - [Python Bootcamp](https://www.byteacademy.co/courses/python-bootcamp)
    - [Data Science Bootcamp](https://www.byteacademy.co/courses/data-science-bootcamp)
    - [Intro to Python](https://www.byteacademy.co/courses/intro-to-python)
- [Career Support](https://www.byteacademy.co/careers-at-byte)
- [APPLY NOW](https://application.byteacademy.co)
- Global 
    - Paraguay
    - India
    - Global

###### 3 min read

# [Validating Form Input With Django](https://www.byteacademy.co/blog/validating-form-input-with-django)

 Aug 12, 2020 9:26:56 AM

- [Tweet](https://twitter.com/share)

Let’s say I’m making a blogging web application using Python and the web framework, Django. I want users to be able to publish “Posts” on my blogging website.

When they enter that “Post” into some sort of input form that I have on my website, I want to check the “Post” before I save it to my database.

This is a common scenario for many Django developers. How do we validate form data before we save it to a database?

There’s two common ways to do it: Either validate the Model or validate the Form.

Django has Forms and Models. Very basically, Forms are where users input data on a web application, and Models and where I actually save my information in my program.

Let’s look first at how to validate the Model:

 

### **Validate the Model:**

My Post model would look something like this, within my models.py file:

```

class Post(models.Model):
    title = models.CharField(max_length=40)
    content = models.CharField(max_length=4000)
    slug = models.SlugField(max_length=40)
    created_at = models.DateTimeField(editable=False)
    updated_at = models.DateTimeField()
    user = models.ForeignKey(
        User,
        null = True,
        default = None,
        on_delete = models.SET_DEFAULT,
    )
```

Now, let’s say I want to validate the title field, so that all users’ Posts must have a title that is at least 5 characters long. Now, still within models.py I could add this function:

```

from django.core.exceptions import ValidationError
```

`def min_validation(value): if len(value) < 5: raise ValidationError("{} is invalid, must have more than 5 characters". format(value))`

This is a function to check if there’s 5 characters in any string. To use this function to validate my model, I could change my Post model by adding two methods, like this:

```

class Post(models.Model):
    title = models.CharField(max_length=40)
    content = models.CharField(max_length=4000)
    slug = models.SlugField(max_length=40)
    created_at = models.DateTimeField(editable=False)
    updated_at = models.DateTimeField()
    user = models.ForeignKey(
        User,
        null = True,
        default = None,
        on_delete = models.SET_DEFAULT,
    )
```

def save(self, \*args, \*\*kwargs):  
self.slug = slugify(self.title)  
self.updated\_at = timezone.now()  
if not self.id:  
self.created\_at = timezone.now()  
self.full\_clean()  
super(Post, self).save(\*args, \*\*kwargs)

```

```

`def clean(self): min_validation(self.title)`

This new Post model has a save() method and a clean() method. You can see that within clean(), I use my min\_validation() function. Now, whenever I save an object of type Post anywhere in my Django application, these functions will first check to see if the title is at least 5 characters.

### **Validate the Form:**

Another way to tackle this problem is to validate the form input as soon as the user enters his/her data.

Within my forms.py file, I have a form that could look like this:

```

class PostForm(forms.ModelForm):
```

def \_\_init\_\_(self, \*args, \*\*kwargs):  
super(MyModelForm, self).\_\_init\_\_(\*args, \*\*kwargs)  
self.fields\["title"\].validators.append(min\_validation)

```

```

`class Meta: model = Post fields = [ "title", "content", ] widgets = { "content": Textarea(attrs={"cols": 50, "rows": 10}), }`

This is Django code that I could use to make a basic form in which users could input a Post title and content. You can see that in the form’s \_\_init\_\_() function, I’ve included the min\_validation function. Note that I’d have to define this min\_validation function elsewhere in forms.py, or I’d have to import it into forms.py if I want this to work.

With this strategy, I’ve added a custom validation function to the ‘title’ field of my Post form.

### **Summary**

Django gives you a few options for defining custom validators in your models and forms. If you have form input that you’d like to check in some way, two options you have are to place your validators on the model or on the form. Both of these will produce the desired outcome. I hope these examples will help you out!

 

 

*Liked what you read? Checkout Byte Academy's [Software Development](https://www.byteacademy.co/courses/software-development)and [Intro to Python](https://www.byteacademy.co/courses/intro-to-python) courses.*

 

###### Topics: [jeff maxim](https://www.byteacademy.co/blog/topic/jeff-maxim) [Python](https://www.byteacademy.co/blog/topic/python) [Programming Tips](https://www.byteacademy.co/blog/topic/programming-tips) [django](https://www.byteacademy.co/blog/topic/django)

#### Written by [Jeff Maxim](https://www.byteacademy.co/blog/author/jeff-maxim)

###### [Previous Post](https://www.byteacademy.co/blog/im-an-engineer-and-im-in-demand-so-pay-me-more)

[![](https://via.placeholder.com/300x150.jpg/e0e7ee)](https://www.byteacademy.co/blog/im-an-engineer-and-im-in-demand-so-pay-me-more)

###### [Engineering Your Job Search](https://www.byteacademy.co/blog/im-an-engineer-and-im-in-demand-so-pay-me-more)

###### [Next Post](https://www.byteacademy.co/blog/fintech-power-plays-asia-hong-kong-singapore)

[![](https://via.placeholder.com/300x150.jpg/e0e7ee)](https://www.byteacademy.co/blog/fintech-power-plays-asia-hong-kong-singapore)

###### [Which Country Will Lead The FinTech Revolution?](https://www.byteacademy.co/blog/fintech-power-plays-asia-hong-kong-singapore)

### Featured

### Sign up for updates

##### Learn More

Learn More

- [Admissions & Tuition](https://www.byteacademy.co/admissions-tuition)
- [Careers at Byte](https://byteacademy.co/careers-at-byte/)
- [Byte Ambassador](https://byteacademy.co/brand-ambassador/)
- [Contact Us](https://meet.byteacademy.co/?hs_preview=XUIOSGQd-26557024777)

##### Get Started

Get Started

- [Intro to Python](https://meet.byteacademy.co/courses/intro-to-python?hs_preview=AZDAyxFU-26462024908&hsLang=en-us)
- [Workshops](https://www.eventbrite.com/o/byte-academy-8388805444)
- [Events](https://www.meetup.com/pro/byte-academy)

##### Stay Informed

Stay Informed

- [Blog](https://byteacademy.co/blog/)
- [Press](https://byteacademy.co/press-page/)

##### Resources

[ByteDev](https://www.bytedev.co/)

[edChain](https://www.edchain.io/)

[Blockchain Lab](https://blokchainlab.byteacademy.co/)

<https://www.facebook.com/byteacademy/> <https://twitter.com/ByteAcademyCo> <https://www.instagram.com/byteacademy/> <https://www.linkedin.com/edu/school?id=171001> <https://www.youtube.com/channel/UCrMcJALnO748TSK27bZQzSg>

[![byte_academy_logo](https://www.byteacademy.co/hs-fs/hubfs/BYTE%20logo%20files/byte_academy_logo.png?width=100&height=129&name=byte_academy_logo.png "byte_academy_logo")](http://sprytelabs.com)

Copyright © 2020 Byte Academy, Inc.

- [Privacy Policy](https://byteacademy.co/privacy-policy/)