Login

Tag "model-forms"

Snippet List

Model Forms: Clean unique field

Often I want fields in my models to be unique - Django's `unique` works too late in model form validation and will throw an exception unless you check for it by hand. This is a bit of code that cleans up the boiler plate of checking if different fields are unique. Set `exclude_initial` to `False` if you want to raise an error if the unique field cannot be set to whatever value the instance had before. **Update** Thanks fnl for rightly pointing out that Django's `unique=True` does check for this - just make sure to pass `instance=obj` when you're initializing your forms. _HOWEVER_ a problem you'll typically run into with this is though you want a field to unique, you also want multiple entries to be able to be `blank`. This can help you!

  • forms
  • model
  • unique
  • model-forms
Read More

1 snippet posted so far.