Reputation: 391
I figured it would be useful to collect all 404 errors and store them in a model.
These errors can/should be useful in writing (or re-writing) urls for designing a new web project. Also, as you might do, people who automatically type in http://www.domian.com/news
or http://www.domian.com/products
or http://www.domian.com/facebook
It would also be useful when people type links in incorrectly and you can develop a redirect for it.
I just don't know how I would execute something like this. Any ideas?
Thanks for your suggestions!
Upvotes: 3
Views: 492
Reputation: 391
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.
Upvotes: 1
Reputation: 9555
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.
Upvotes: 4