Showing custom model validation exceptions in the Django admin site

后端 未结 4 1269
悲&欢浪女
悲&欢浪女 2021-02-07 00:27

I have a booking model that needs to check if the item being booked out is available. I would like to have the logic behind figuring out if the item is available centralised so

4条回答
  •  伪装坚强ぢ
    2021-02-07 00:46

    I've also tried to solve this and there is my solution- in my case i needed to deny any changes in related_objects if the main_object is locked for editing.

    1) custom Exception

    class Error(Exception):
        """Base class for errors in this module."""
        pass
    
    class EditNotAllowedError(Error):
        def __init__(self, msg):
            Exception.__init__(self, msg)
    

    2) metaclass with custom save method- all my related_data models will be based on this:

    class RelatedModel(models.Model):
        main_object = models.ForeignKey("Main")
    
        class Meta:
            abstract = True
    
        def save(self, *args, **kwargs):
            if self.main_object.is_editable():
                super(RelatedModel, self).save(*args, **kwargs)
            else:
                raise EditNotAllowedError, "Closed for editing"
    

    3) metaform - all my related_data admin forms will be based on this (it will ensure that admin interface will inform user without admin interface error):

    from django.forms import ModelForm, ValidationError
    ...
    class RelatedModelForm(ModelForm):
        def clean(self):
        cleaned_data = self.cleaned_data
        if not cleaned_data.get("main_object")
            raise ValidationError("Closed for editing")
        super(RelatedModelForm, self).clean() # important- let admin do its work on data!        
        return cleaned_data
    

    To my mind it is not so much overhead and still pretty straightforward and maintainable.

提交回复
热议问题