[Django]-Save 404 Error's URL in Django in models

4👍

The easiest way to do that would be to write custom middleware that handles 404s. See the Django documentation on middleware.

A very simple example middleware class that triggers on a 404:

from django.http import HttpResponseNotFound

class Catch404Middleware(object):
    def process_response(self, request, response):
        if isinstance(response, HttpResponseNotFound):
            print "That was a 404!"
        return response

Remember you’ll need to install this class into your MIDDLEWARE_CLASSES in settings.py.

1👍

Thanks to a previous answer, I’ve made this:

#middleware.py (Under the Analytics App)


from django.http import HttpResponseNotFound, HttpRequest
from analytics.models import Site_Error

class Catch404Middleware(object):
     def process_response(self, request, response):
         if isinstance(response, HttpResponseNotFound):
        try:
            new_save,created = Site_Error.objects.get_or_create(error=request.path)
            new_save.times += 1
            new_save.save()
        except:
           new_save = False
    return response

#models.py (Ananlytics App)

class Site_Error(models.Model):
    error = models.CharField(max_length=8000)
    times = models.IntegerField(default=0)
    timestamp = models.DateTimeField(auto_now_add=True)

    class Meta:
         ordering = ('-timestamp',)
         verbose_name = "Error"
         verbose_name_plural = "Errors"

     def __unicode__(self):
         return self.error


#in settings.py 
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'analytics.middleware.Catch404Middleware',
)

This code will save all requested paths into the Site_Error model. There is much more you can do with this so I suggest you look in Django documentation on middleware just as recommended by an answer before.

Leave a comment