Created
November 30, 2011 23:04
-
-
Save dgouldin/1411676 to your computer and use it in GitHub Desktop.
Abstract model class which validates on save using a default ModelForm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from django import forms | |
from django.forms.models import modelform_factory | |
class ValidatingModel(models.Model): | |
class Meta: | |
abstract = True | |
def __init__(self, *args, **kwargs): | |
self.model_form_class = modelform_factory(self.__class__) | |
return super(ValidatingModel, self).__init__(*args, **kwargs) | |
def save(self, *args, **kwargs): | |
data = {} | |
for field_name, field in self.model_form_class.base_fields.items(): | |
data[field_name] = getattr(self, field_name) | |
form = self.model_form_class(instance=self, data=data) | |
if form.is_valid(): | |
super(ValidatingModel, self).save(*args, **kwargs) | |
else: | |
self.validation_errors = form.errors | |
raise forms.ValidationError(form.errors) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment