Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 434869
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T20:19:06+00:00 2026-05-12T20:19:06+00:00

Where should the validation of model fields go in django? I could name at

  • 0

Where should the validation of model fields go in django?

I could name at least two possible choices: in the overloaded .save() method of the model or in the .to_python() method of the models.Field subclass (obviously for that to work you must write custom fields).

Possible use cases:

  • when it is absolutely neccessary to ensure, that an empty string doesn’t get written into the database (blank=False keyword argument doesn’t work here, it is for form validation only)
  • when it is neccessary to ensure, that “choices” keyword argument gets respected on a db-level and not only in admin interface (kind of emulating a enum datatype)

There is also a class-level attribute empty_strings_allowed in the models.Field base class definition and derived classes happily override it, however it doesn’t seem to produce any effect on the database level, meaning I can still construct a model with empty-string fields and save it to the database. Which I want to avoid (yes, it is neccessary).

Possible implementations are

on the field level:

class CustomField(models.CharField):
    __metaclass__ = models.SubfieldBase
    def to_python(self, value):
        if not value:
            raise IntegrityError(_('Empty string not allowed'))
        return models.CharField.to_python(self, value)

on the model level:

class MyModel(models.Model)
    FIELD1_CHOICES = ['foo', 'bar', 'baz']
    field1 = models.CharField(max_length=255, 
               choices=[(item,item) for item in FIELD1_CHOICES])

    def save(self, force_insert=False, force_update=False):
        if self.field1 not in MyModel.FIELD1_CHOICES:
            raise IntegrityError(_('Invalid value of field1'))
        # this can, of course, be made more generic
        models.Model.save(self, force_insert, force_update)

Perhaps, I am missing something and this can be done easier (and cleaner)?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T20:19:07+00:00Added an answer on May 12, 2026 at 8:19 pm

    Django has a model validation system in place since version 1.2.

    In comments sebpiq says “Ok, now there is a place to put model validation … except that it is run only when using a ModelForm! So the question remains, when it is necessary to ensure that validation is respected at the db-level, what should you do? Where to call full_clean?”

    It’s not possible via Python-level validation to ensure that validation is respected on the db level. The closest is probably to call full_clean in an overridden save method. This isn’t done by default, because it means everybody who calls that save method had now better be prepared to catch and handle ValidationError.

    But even if you do this, someone can still update model instances in bulk using queryset.update(), which will bypass this validation. There is no way Django could implement a reasonably-efficient queryset.update() that could still perform Python-level validation on every updated object.

    The only way to really guarantee db-level integrity is through db-level constraints; any validation you do through the ORM requires the writer of app code to be aware of when validation is enforced (and handle validation failures).

    This is why model validation is by default only enforced in ModelForm – because in a ModelForm there is already an obvious way to handle a ValidationError.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: Django dynamic model fields Good Morning guys! Scenario is the following. For
Two function should be implemented, and I am wondering what type of validation I
When validation fails, which one I should return? View(); or View(model); ? I notice
I'm having a problem with validation in my RoR Model: def save self.accessed =
I have created a model with several fields that should accept the same data
I have a question: How should I name apps, views, models, forms, fields, etc?
My User model contains :name, :email, and :password fields. All 3 have validations for
Should you do validation on the server side, or is it ok to just
I have some validation code which should display the max / min of a
How can I force validation when user clicks button? One would think this should

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.