Django Admin Intermittently Returning 404 On Model

2019-05-07 14:12发布

问题:

We're using the Django Admin to maintain some data that's exported to a few of our sites. Sometimes when clicking through the standard changelist view to get a model edit form instead of being routed to the correct page we're getting the Django 404 page/template.

It was happening somewhat sporatically, and we could for a while reproduce it by reloading three times:

  • First F5: 404
  • Second F5: 404
  • Third F5: Object change form loads correctly

But lately it's been returning 404 more often than not. It seems to reduce the odds of returning 404 when we bounce apache (gracefully) and gets worse (again, seemingly) with more requests.

Running Django 1.2.1 on Fast-CGI/MySQL 5.1.x

FWIW, I can't reproduce the problem on my VM, but I'm running mod_wsgi there and have Debug=True set in the settings. Otherwise the code and database is identical.

回答1:

I had this same problem. The solution for me was to move my calls to admin.site.register() to admin.py. With DEBUG set to false, your models are lazily loaded, so the registration calls don't always get made. Apparently admin.py is always loaded at init time, however.



回答2:

i had same problem until last week. after i track this error for couple of months and i found 404 raising at django source code.

i modified the file /path/to/django/contrib/admin/options.py get_object() method of ModuleAdmin class. Note: i use Django 1.3.1

somehow django cannot find object with pk object_id in queryset. so i modified it like this:

def get_object(self, request, object_id):
    ....
    queryset = self.queryset(request)
    model = queryset.model
    obj = None

    #first search the object with original way
    try:
        object_id = model._meta.pk.to_python(object_id)
        obj = queryset.get(pk=object_id)
    except:
        #print "DEBUG: > first try does not exist (%s)" % str(object_id)
        obj = None

    if obj is None: 
        #if object doesn't exist in queryset, search in db
        try:
            object_id = model._meta.pk.to_python(object_id)
            obj = model.objects.get(pk=object_id)
            #print "DEBUG: > second try found %s" % str(obj)
        except (model.DoesNotExist, ValidationError):
            #print "DEBUG: > second try does not exist"
            obj = None
    return obj

i know it's not a good thing to change something in django's source, so use at your own risk !



回答3:

See if the alternate WSGI script at the end of:

http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html

makes a difference.