mod_python error when debug=False

27 views
Skip to first unread message

Michael Repucci

unread,
Feb 27, 2009, 11:46:07 AM2/27/09
to Django users
I've been trying to put my site up live, and keep coming across an
error (on any page on the site) whenever I set debug=False in
settings.py. With the development server, or with debug=True on the
production server, I don't have this problem at all. I searched for a
similar problem on djangoproject and here, and found only a closed
ticket (http://code.djangoproject.com/ticket/8569) with a changeset
(http://code.djangoproject.com/changeset/8605) that I assume was built
into the version I'm using (1.0.2-final). I downloaded the changeset
anyway, and substituted it, but it didn't help. Below is my mod_python
traceback. Any help would be GREATLY appreciated! Thanks!!

MOD_PYTHON ERROR

ProcessId: 1564
Interpreter: 'poseidon.sunyopt.edu'

ServerName: 'poseidon.sunyopt.edu'
DocumentRoot: 'C:/websites/wwwroot'

URI: '/backuslab/'
Location: '/backuslab/'
Directory: None
Filename: 'C:/websites/wwwroot/BackusLab/'
PathInfo: ''

Phase: 'PythonHandler'
Handler: 'django.core.handlers.modpython'

Traceback (most recent call last):

File "C:\Program Files\Python\Lib\site-packages\mod_python
\importer.py", line 1537, in HandlerDispatch
default=default_handler, arg=req, silent=hlist.silent)

File "C:\Program Files\Python\Lib\site-packages\mod_python
\importer.py", line 1229, in _process_target
result = _execute_target(config, req, object, arg)

File "C:\Program Files\Python\Lib\site-packages\mod_python
\importer.py", line 1128, in _execute_target
result = object(arg)

File "c:\program files\python\Lib\site-packages\django\core\handlers
\modpython.py", line 228, in handler
return ModPythonHandler()(req)

File "c:\program files\python\Lib\site-packages\django\core\handlers
\modpython.py", line 201, in __call__
response = self.get_response(request)

File "c:\program files\python\Lib\site-packages\django\core\handlers
\base.py", line 128, in get_response
return self.handle_uncaught_exception(request, resolver, exc_info)

File "c:\program files\python\Lib\site-packages\django\core\handlers
\base.py", line 159, in handle_uncaught_exception
callback, param_dict = resolver.resolve500()

File "c:\program files\python\Lib\site-packages\django\core
\urlresolvers.py", line 218, in resolve500
return self._resolve_special('500')

File "c:\program files\python\Lib\site-packages\django\core
\urlresolvers.py", line 207, in _resolve_special
callback = getattr(self.urlconf_module, 'handler%s' % view_type)

File "c:\program files\python\Lib\site-packages\django\core
\urlresolvers.py", line 198, in _get_urlconf_module
self._urlconf_module = __import__(self.urlconf_name, {}, {}, [''])

File "c:/websites/django/backuslab\laboratory\urls.py", line 5, in
<module>
admin.autodiscover()

File "c:\program files\python\Lib\site-packages\django\contrib\admin
\__init__.py", line 40, in autodiscover
__import__("%s.admin" % app)

File "c:/websites/django/backuslab\laboratory\people\admin.py", line
107, in <module>
class PersonForm(forms.ModelForm):

File "c:\program files\python\Lib\site-packages\django\forms
\models.py", line 195, in __new__
opts.exclude, formfield_callback)

File "c:\program files\python\Lib\site-packages\django\forms
\models.py", line 162, in fields_for_model
formfield = formfield_callback(f)

File "c:\program files\python\Lib\site-packages\django\forms
\models.py", line 177, in <lambda>
lambda f: f.formfield())

File "c:\program files\python\Lib\site-packages\django\db\models
\fields\related.py", line 914, in formfield
defaults = {'form_class': forms.ModelMultipleChoiceField,
'queryset': self.rel.to._default_manager.complex_filter
(self.rel.limit_choices_to)}

AttributeError: 'str' object has no attribute '_default_manager'

Karen Tracey

unread,
Feb 27, 2009, 11:38:20 PM2/27/09
to django...@googlegroups.com
On Fri, Feb 27, 2009 at 11:46 AM, Michael Repucci <mic...@repucci.org> wrote:

I've been trying to put my site up live, and keep coming across an
error (on any page on the site) whenever I set debug=False in
settings.py. With the development server, or with debug=True on the
production server, I don't have this problem at all. I searched for a
similar problem on djangoproject and here, and found only a closed
ticket (http://code.djangoproject.com/ticket/8569) with a changeset
(http://code.djangoproject.com/changeset/8605) that I assume was built
into the version I'm using (1.0.2-final). I downloaded the changeset
anyway, and substituted it, but it didn't help. Below is my mod_python
traceback. Any help would be GREATLY appreciated! Thanks!!

That changeset was before 1.0, so yes you should have already had it.  You seem to have found a different path to the same ultimate error situation.


This is the first indication of a problem, something raised an exception trying to generate a response.  Don't know if it is the same as the exception you are ultimately seeing or if something else went wrong.
 

 File "c:\program files\python\Lib\site-packages\django\core\handlers
\base.py", line 159, in handle_uncaught_exception
   callback, param_dict = resolver.resolve500()

 File "c:\program files\python\Lib\site-packages\django\core
\urlresolvers.py", line 218, in resolve500
   return self._resolve_special('500')

 File "c:\program files\python\Lib\site-packages\django\core
\urlresolvers.py", line 207, in _resolve_special
   callback = getattr(self.urlconf_module, 'handler%s' % view_type)

 File "c:\program files\python\Lib\site-packages\django\core
\urlresolvers.py", line 198, in _get_urlconf_module
   self._urlconf_module = __import__(self.urlconf_name, {}, {}, [''])

So here the code that is attempting to handle the uncaught exception goes to load your url configuration as part of figuring what to call to generate the 500 response.


 File "c:/websites/django/backuslab\laboratory\urls.py", line 5, in
<module>
   admin.autodiscover()
 
File "c:\program files\python\Lib\site-packages\django\contrib\admin
\__init__.py", line 40, in autodiscover
   __import__("%s.admin" % app)

And that calls admin.autodiscover(), which was also present in the earlier tracebacks.  But after that the traceback from #8596 doesn't match well with what we see called here.  The #8596 traceback proceeded into validate(), which is only called if DEBUG is True, and that is where the fix was put.  In this case you're not going into validate(), but rather are encountering the error just on defining a ModelForm.
 

 File "c:/websites/django/backuslab\laboratory\people\admin.py", line
107, in <module>
   class PersonForm(forms.ModelForm):

 File "c:\program files\python\Lib\site-packages\django\forms
\models.py", line 195, in __new__
   opts.exclude, formfield_callback)

 File "c:\program files\python\Lib\site-packages\django\forms
\models.py", line 162, in fields_for_model
   formfield = formfield_callback(f)

 File "c:\program files\python\Lib\site-packages\django\forms
\models.py", line 177, in <lambda>
   lambda f: f.formfield())

 File "c:\program files\python\Lib\site-packages\django\db\models
\fields\related.py", line 914, in formfield
   defaults = {'form_class': forms.ModelMultipleChoiceField,
'queryset': self.rel.to._default_manager.complex_filter
(self.rel.limit_choices_to)}

AttributeError: 'str' object has no attribute '_default_manager'

Some details of your models and admin.py might help isolate what is going on here.   You're apparently going down some path that is assuming apps have been fully loaded when they are not.  You are going down this path while the code is attempting to handle a 500 error -- I don't know if the first error is the same (in which case there's likely something in your model/admin defs that seems to be not handled properly, at least when DEBUG is False), or if the first error interrupted/prevented the full loading of models and that's why the subsequent code runs into trouble. 

Karen

Michael A. Repucci

unread,
Mar 2, 2009, 2:36:43 PM3/2/09
to django...@googlegroups.com
Thanks for walking me through the traceback Karen. I'm happy to post my models.py and admin.py code here (or whatever else might help), but I don't ever explicitly check settings.DEBUG in any of my code, so I'm at a bit of a loss where the error might be coming from. Any further suggestions?

#people/models.py

from django.db import models
from django.contrib.auth.models import User
from django.contrib.localflavor.us.models import PhoneNumberField

class Contact(models.Model):
    """
    The Contact model represents contact information.
    """
    owner = models.ForeignKey(User,blank=False) #relationship field
    address = models.TextField("Address (W)",default="33 West 42nd Street\nNew York, NY 10036",blank=False)
    phone = PhoneNumberField("Phone (W)",blank=True)
    fax = PhoneNumberField("Fax (W)",blank=True)
    email = models.EmailField("Email",blank=True)
    website = models.URLField("Website",blank=True)
    home = models.TextField("Address (H)",blank=True)
    line = PhoneNumberField("Phone (H)",blank=True)
    mobile = PhoneNumberField("Mobile",blank=True)
    emergency = models.TextField("Emergency Contact",blank=True)
    def __unicode__(self):
        return "\n".join([i for i in [self.address, self.phone, self.fax, self.email, self.website, self.home, self.line, self.mobile, self.emergency] if i])

class Person(models.Model):
    """
    The Person model represents a person.
    """
    owner = models.ForeignKey(User,blank=False) #relationship field
    first_name = models.CharField("First Name",max_length=30,blank=False)
    middle_name = models.CharField("Middle Name",max_length=30,blank=True)
    last_name = models.CharField("Last Name",max_length=60,blank=False)
    degree = models.CharField("Degree(s)",max_length=12,blank=True)
    title = models.ForeignKey("Title",verbose_name="Title",blank=False) #relationship field
    date_start = models.DateField("Start Date",blank=False)
    date_end = models.DateField("End Date",help_text="Please approximate and change upon departure.",blank=False)
    contact = models.ForeignKey("Contact",verbose_name="Contact",blank=False) #relationship field
    publications = models.ManyToManyField("publications.Publication",verbose_name="Publication(s)",blank=True) #relationship field
    cv = models.FileField("CV",upload_to="cvs",blank=True)
    image = models.ImageField("Photo",upload_to="images/people",blank=True)
    statement = models.TextField("Personal Statement",help_text="This text may include HTML formatting.",blank=True)
    def __unicode__(self):
        return " ".join([i for i in [self.first_name, self.middle_name, self.last_name] if i])
    class Meta:
        verbose_name_plural = "People"

class Title(models.Model):
    """
    The Title model represents a job title.
    """
    name = models.CharField("Title",max_length=50,blank=False)
    def __unicode__(self):
        return self.name


#people/admin.py

from laboratory.people.models import Contact, Person, Title
from django.contrib import admin
from django import forms
from html5lib import HTMLParser, sanitizer, treewalkers, serializer
import re

def save_model_method(self, request, obj, form, change):
    """
    The save_model_method is used by the ModelAdmin classes below
    to override their save_model methods. See the documentation at
    http://docs.djangoproject.com/en/dev/ref/contrib/admin/#save-model-self-request-obj-form-change.
    """
    if isinstance(obj, Person) and obj.pk:
        person = Person.objects.get(pk=obj.pk)
        if person.cv and 'cv' in form.changed_data:
            person.cv.delete() #delete old file
        if person.image and 'image' in form.changed_data:
            person.image.delete() #delete old file
    if not change:
        obj.owner = request.user
    obj.save()

def queryset_method(self, request, queryClass):
    """
    The queryset_method is used by the ModelAdmin classes below to
    override their queryset methods. This method is undocumented
    but can be found in django/contrib/admin/options.py.
    """
    if request.user.is_superuser:
        return queryClass.objects.all()
    else:
        return queryClass.objects.filter(owner=request.user)

def has_add_permission_method(self, request, superClass):
    """
    The has_add_permission_method is used by the ModelAdmin classes
    below to override their has_add_permission methods. This method
    is undocumented but can be found in
    django/contrib/admin/options.py.
    """
    has_class_permission = super(type(self), self).has_add_permission(request)
    has_no_obj = superClass.objects.filter(owner=request.user).count()==0
    if has_class_permission and (request.user.is_superuser or has_no_obj):
        return True
    else:
        return False

def has_change_permission_method(self, request, obj=None):
    """
    The has_change_permission_method is used by the ModelAdmin
    classes below to override their has_change_permission methods.
    This method is undocumented but can be found in
    django/contrib/admin/options.py.
    """
    has_class_permission = super(type(self), self).has_change_permission(request, obj)
    if has_class_permission and (obj is None or request.user.is_superuser or request.user.id==obj.owner.id):
        return True
    else:
        return False

def get_form_method(self, request, obj, exclude, **kwargs):
    """
    The get_form_method is used by the ModelAdmin classes below to
    override their get_form methods. This method is undocumented
    but can be found in django/contrib/admin/options.py.
    """
    if request.user.is_superuser:
        self.exclude = None
    else:
        self.exclude = exclude
    return super(type(self), self).get_form(request, obj, **kwargs)

def changelist_view_method(self, request, extra_context, exclude, list_display):
    """
    The changelist_view_method is used by the ModelAdmin classes
    below to override their changelist_view methods. This method
    is undocumented but can be found in
    django/contrib/admin/options.py.
    """
    if request.user.is_superuser:
        self.list_display = exclude + list_display
    else:
        self.list_display = list_display
    return super(type(self), self).changelist_view(request, extra_context)

class ContactAdmin(admin.ModelAdmin):
    fieldsets = (
        ('Work (public)', {'fields': ('address', 'phone', 'fax', 'email', 'website',)}),
        ('Home (private)', {'fields': ('home', 'line', 'mobile', 'emergency',)}),
    )
    exclude_list = ('owner',) #custom field - see get_form
    list_display_list = ('address', 'phone', 'fax', 'email', 'website', 'home', 'line', 'mobile', 'emergency',) #custom field - see changelist_view
    search_fields = ['address', 'phone', 'fax', 'email', 'website', 'home', 'line', 'mobile', 'emergency',]
    save_model = save_model_method
    has_change_permission = has_change_permission_method
    def queryset(self, request):
        return queryset_method(self, request, Contact)
    def has_add_permission(self, request):
        return has_add_permission_method(self, request, Contact)
    def get_form(self, request, obj=None, **kwargs):
        return get_form_method(self, request, obj, self.exclude_list, **kwargs)
    def changelist_view(self, request, extra_context=None):
        return changelist_view_method(self, request, extra_context, self.exclude_list, self.list_display_list)

class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
    def clean_cv(self):
        cv = self.cleaned_data['cv']
        if cv:
            cv.name = re.sub(r"(?i)(?P<ext>(?:cgi|htaccess|php[0-9s]?|[ps]html?|pl|pyc?|rb)(?:\..+)?)$",
                             r"\g<ext>.txt",
                             cv.name)
        return cv
    def clean_statement(self):
        statement = self.cleaned_data['statement']
        parser = HTMLParser(tokenizer=sanitizer.HTMLSanitizer)
        tree = parser.parseFragment(statement)
        walker = treewalkers.getTreeWalker("simpletree")
        stream = walker(tree)
        serial = serializer.xhtmlserializer.XHTMLSerializer(omit_optional_tags=True)
        if statement:
            cleaned = serial.render(stream)
        else:
            cleaned = ""
        return cleaned

class PersonAdmin(admin.ModelAdmin):
    exclude_list = ('owner',) #custom field - see get_form
    list_display_list = ('first_name', 'middle_name', 'last_name', 'degree', 'title',
                         'date_start', 'date_end', 'contact', 'cv', 'image', 'statement',) #custom field - see changelist_view
    list_filter = ['title',]
    search_fields = ['first_name', 'middle_name', 'last_name', 'degree', 'title',
                     'date_start', 'date_end',]
    filter_vertical = ['publications',]
    form = PersonForm
    save_model = save_model_method
    has_change_permission = has_change_permission_method
    def queryset(self, request):
        return queryset_method(self, request, Person)
    def has_add_permission(self, request):
        return has_add_permission_method(self, request, Person)
    def get_form(self, request, obj=None, **kwargs):
        return get_form_method(self, request, obj, self.exclude_list, **kwargs)
    def changelist_view(self, request, extra_context=None):
        return changelist_view_method(self, request, extra_context, self.exclude_list, self.list_display_list)

class TitleAdmin(admin.ModelAdmin):
    list_display = ('name',)
    search_fields = ['name']

admin.site.register(Contact, ContactAdmin)
admin.site.register(Person, PersonAdmin)
admin.site.register(Title, TitleAdmin)

Danny Brown

unread,
Mar 2, 2009, 3:17:53 PM3/2/09
to django...@googlegroups.com
using syntax like this : contact = models.ForeignKey("Contact" was
causing me to fail earlier today at the exact same line.
her response to me was "Why are you using quoted strings instead of
direct references to the target models here and in the OneToOneField
in VoipGateway? I don't understand why it isn't working, but it also
doesn't appear to be necessary in your case (you don't have circular
references"

sure enough, I got rid of the quoted strings and it began to work.
Worth a shot anyway, if you don't need the circular references.

Michael A. Repucci

unread,
Mar 2, 2009, 3:43:41 PM3/2/09
to django...@googlegroups.com
Hey thanks Danny!! That worked! The quoted strings syntax should be permissible, and works just fine with DEBUG=True, or on the development server. I'd say this should be a new ticket, but what do I know. I'm just a user not a developer. Anyway, thanks again!

Danny Brown

unread,
Mar 2, 2009, 3:48:41 PM3/2/09
to django...@googlegroups.com
Thanks to Karen, She figured it out. I guess she will know if it
should be a ticket. I am like you. I sure don't know.

Karen Tracey

unread,
Mar 2, 2009, 4:43:06 PM3/2/09
to django...@googlegroups.com
On Mon, Mar 2, 2009 at 3:48 PM, Danny Brown <dan...@gmail.com> wrote:

Thanks to Karen, She figured it out. I guess she will know if it
should be a ticket. I am like you. I sure don't know.

Probably worth a ticket so it doesn't get forgotten; I won't be able to experiment with an Apache setup until the weekend.  I think the quoted-string version should be working even in non-circular cases where you don't absolutely need it, but don't really have time to look into it deeply at the moment.  It would be useful if you (or whoever opens a ticket) could pare down the models involved into a minimal example that fails for recreation purposes.

Thanks,
Karen

Danny Brown

unread,
Mar 2, 2009, 5:32:56 PM3/2/09
to django...@googlegroups.com
I guess I will try tomorrow . Don't know if I know enough about Django
to make an intelligent submittal but will try.
Reply all
Reply to author
Forward
0 new messages