I’m working in a Django project. I’ve created a model to save the last 50 errors that happen.
models.py
class Error(models.Model):
ERROR_TYPE_CHOICES = [
('ERROR', 'ERROR'),
('WARNING', 'WARNING'),
]
user_mail = models.CharField(max_length=500, blank=True, null=True)
error_type = models.CharField(max_length=7, choices=ERROR_TYPE_CHOICES)
error_message = models.CharField(max_length=1000, blank=True, null=True)
error_message_detail = models.CharField(max_length=500, blank=True, null=True)
created_at = models.DateTimeField(default=timezone.now)
# Static field for maximum errors limit
max_errors = 50
def __str__(self):
return f"{self.error_type}: {self.error_message}"
class Meta:
ordering = ['-created_at'] # Order by descending creation date
@classmethod
def check_and_trim(cls):
# # Obtain all errors ordered by creation date
errors = cls.objects.all().order_by('-created_at')
# If there are more than 50 errors, delete the older ones
if errors.count() > cls.max_errors:
errors_to_delete = errors[cls.max_errors:]
for error in errors_to_delete:
error.delete()
admin.py
class ErrorAdmin(admin.ModelAdmin):
list_display = ('user_mail', 'error_type', 'error_message', 'error_message_detail', 'created_at')
admin.site.register(Error, ErrorAdmin)
So as you can see when there are more than 50 errors the oldest one is erased so that the new one can be saved.
In the future maybe is needed to be saved more than 50 errors, so instead of changing the code I’d like to add a feature now so in the localhost:8000/admin/Error
you can input how many errors you want to be saved.
You can’t do this here and this handling viewing the records in the database and according to you, you delete the oldest to put the new error, so you don’t have more than 50 records.
This needs to be saved in your settings file and to allow the staff to change it, use django-constance package to manage this.
On a side note, Sentry will be much better in this, and it gives alot of insights regarding the request and variables.Also, you can host yourself (for free) if you don’t want to send your user data out of your infrastructure.