Django: Form.clean() is being called even though required fields are empty

So I decided to randomly check some code by submitting an empty form. To my surprise, Form.clean() was being called even though the required fields weren't valid. I was certain it was a core Django bug.

Hello Twig, I'd like to play a game ...

It took a bit of thinking but I finally understand now. It's meant to work like that.

Wait, hear me out!

Most people would do this:

def clean(self):
data = self.cleaned_data
country = data['country']

Assuming that the required field "country" is set, but that's not true.

The framework is so lenient that it allows you to raise custom error messages even if the required fields aren't filled in, just in case you wanted it to.

That's ok, Uncle Twig has a fix for you and it's only 2 lines long.

To remedy this, make sure you do this on every custom Form.clean() function!

def clean(self):
if self.errors:
return self.cleaned_data

data = self.cleaned_data
# ...

That's it! At the start, if there's ANY errors at all, simply don't bother. No more invalid key exceptions.

Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog