0👍
Thanks to @FernandoFreitasAlves I could write a solution.
I realised that my model can also be loaded from a file and then stored in the DB, without the CRUD admin page, so I also overide the save()
method.
def save(self, *args, **kwargs):
xml = "<screen>" + self.content + "</screen>"
parseString(xml.encode("utf-8"))
super(Screen, self).save(*args, **kwargs)
def clean(self):
try:
from xml.dom.minidom import parseString
doc = parseString(self.content)
except Exception, e:
from django import forms
raise forms.ValidationError("It's not a XML")
super(Screen,self).clean()
I think I don’t want to overide the full_clean()
method. I can’t see a reason for that. The docs (https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.full_clean) say
This method calls Model.clean_fields(), Model.clean(), and
Model.validate_unique(), in that order and raises a ValidationError
that has a message_dict attribute containing errors from all three
stages.
1👍
I think you may use the clean method inside your models, in that way you will validate your data in the admin, just like the other admin fields
Inside your Model
:
def clean(self):
try:
from xml.dom.minidom import parseString
doc = parseString(self.content)
except Exception, e:
from django import forms
raise forms.ValidationError(u"It's not a XML")
super(YourModel,self).clean()
def full_clean(self, exclude=None):
return self.clean()
reference: https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.clean_fields
- [Answer]-Not getting past form.is_valid to process form in django view
- [Answer]-Run method on session expire Django
- [Answer]-.pyc files don't get updated (only in Django)