Community site: login faq

One of my Django applications is working fine with DEBUG=True, but throws a 500 FieldError when DEBUG=False. (I've posted a detailed explanation here.)

I believe I have ALLOWED HOSTS set correctly (it's set to '.mprsoftball.org', and it has worked with '*' as part of troubleshooting.)

It looks like the problem is with the Game class of gamemaker.models. I've tried various code tweaks, but nothing has worked. What's especially mystifying is why it seems to load correctly with DEBUG=True, but fails with DEBUG=False.

The Trackback,

Traceback (most recent call last):

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/core/handlers/base.py", line 111, in get_response
   response = callback(request, *callback_args, **callback_kwargs)

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/contrib/admin/options.py", line 366, in wrapper
   return self.admin_site.admin_view(view)(*args, **kwargs)

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/utils/decorators.py", line 91, in _wrapped_view
   response = view_func(request, *args, **kwargs)

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/views/decorators/cache.py", line 89, in _wrapped_view_func
   response = view_func(request, *args, **kwargs)

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/contrib/admin/sites.py", line 196, in inner
   return view(request, *args, **kwargs)

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/utils/decorators.py", line 25, in _wrapper
   return bound_func(*args, **kwargs)

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/utils/decorators.py", line 91, in _wrapped_view
   response = view_func(request, *args, **kwargs)

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/utils/decorators.py", line 21, in bound_func
   return func(self, *args2, **kwargs2)

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/db/transaction.py", line 224, in inner
   return func(*args, **kwargs)

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/contrib/admin/options.py", line 1061, in change_view
   form = ModelForm(instance=obj)

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/forms/models.py", line 238, in __init__
   object_data = model_to_dict(instance, opts.fields, opts.exclude)

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/forms/models.py", line 128, in model_to_dict
   data[f.name] = [obj.pk for obj in f.value_from_object(instance)]

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/db/models/fields/related.py", line 1272, in value_from_object
   return getattr(obj, self.attname).all()

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/db/models/manager.py", line 116, in all
   return self.get_query_set()

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/db/models/fields/related.py", line 567, in get_query_set
   return super(ManyRelatedManager, self).get_query_set().using(db)._next_is_sticky().filter(**self.core_filters)

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/db/models/query.py", line 624, in filter
   return self._filter_or_exclude(False, *args, **kwargs)

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/db/models/query.py", line 642, in _filter_or_exclude
   clone.query.add_q(Q(*args, **kwargs))

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/db/models/sql/query.py", line 1250, in add_q
   can_reuse=used_aliases, force_having=force_having)

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/db/models/sql/query.py", line 1122, in add_filter

 File "/home/bwareham/webapps/mprsb/lib/python2.7/django/db/models/sql/query.py", line 1316, in setup_joins
   "Choices are: %s" % (name, ", ".join(names)))

FieldError: Cannot resolve keyword 'game' into field. Choices are: Hall of Fame, active, alias, battingchamps, bombat, captains, firstName, goldengloves, id, lastName, mostimproved, mvp, photo, rookies, roster, sex, walker, whippet

The model,

from django.db import models
from django.forms import ModelForm
from time import strftime
from rostermaker.models import Player
from django.core.exceptions import ValidationError
from django.utils import timezone

class Game(models.Model):
    when = models.DateTimeField(unique = True)
    opponent = models.CharField(max_length = 50, default="TBD")
    location = models.CharField(max_length = 50)
    RosterRulesOn = models.BooleanField('Roster rules', default = 'True', help_text = "Roster size and gender ratio rules will be enforced when checked")
    players = models.ManyToManyField(Player, limit_choices_to={'id__in': Player.objects.filter(active='True')}, null=True, blank=True )
    scoreMPR = models.IntegerField(max_length = 2, verbose_name = "MPR", null=True, blank=True,)
    scoreOPP = models.IntegerField(max_length = 2, verbose_name = "Opponent", null=True, blank=True,)

    def __unicode__(self):
        when = timezone.localtime(self.when)
        return when.strftime('%a, %b %d, %Y %I:%M %p')

class Stat(models.Model):
    g = models.ForeignKey(Game, related_name = 'stat_game')
    player = models.ForeignKey(Player, related_name = 'stat_player', limit_choices_to={'active': True})
    AB = models.PositiveSmallIntegerField()
    single = models.PositiveSmallIntegerField(null=True, blank=True)
    double = models.PositiveSmallIntegerField(null=True, blank=True)
    triple = models.PositiveSmallIntegerField(null=True, blank=True)
    HR = models.PositiveSmallIntegerField(null=True, blank=True)
    SAC = models.PositiveSmallIntegerField(null=True, blank=True)
    BB = models.PositiveSmallIntegerField(null=True, blank=True)
    SO = models.PositiveSmallIntegerField(null=True, blank=True)
    R = models.PositiveSmallIntegerField(null=True, blank=True)
    RBI = models.PositiveSmallIntegerField(null=True, blank=True)

class GameRosterForm(ModelForm):
    class Meta:
        model = Game

    def clean(self):
        super(GameRosterForm, self).clean()
        players = self.cleaned_data.get('players', None)
        RosterRulesOn = self.cleaned_data.get('RosterRulesOn', None)
        women = [player for player in players if player.sex=='F']
        women_count = len(women)
        total = len(players)
        if total != 0:
            womenPct = int((len(women)/float(total))*100)
            womenPct = 0
        if RosterRulesOn is True and total != 0 and total < 8:
            raise ValidationError('Rosters must have at least 8 players. You have only selected %s.' % total) 
        if RosterRulesOn is True and total > 18:
            raise ValidationError('Rosters cannot have more than 18 players. You have selected %s.' % total)
        if RosterRulesOn is True and total != 0 and womenPct < 40:
            raise ValidationError('Women must make up at least 40 percent of roster. They only constitute %s percent now.' % (womenPct))   
        return self.cleaned_data

Here's my app structure:

    /rostermaker (for managing player info)
        Classes: Player
                 HOF (w/ foreign key to Player, related name 'Hall of Fame')
    /gamemaker (for scheduling games and keeping track of player statistics)
        Classes: Game
                 Stat (w/ foreign keys to Game and Player)
                 GameRosterForm (for validating rules about roster size and gender ratios)
    /photo (for managing photos)
        Classes: Photo (w/ M2M to Player to allow tagging of photos)
    /season (for managing historical info about seasons)
        Classes: Season (w/ a bunch of M2M to Player)
    /section (for managing text info on various site sections)
        Classes: Page
                 Item (w/ foreign key to Page)

The field options in the last line of the traceback come from the Player and HOF classes of the rostermaker model, the photo model, and the Season class of the season model.

asked 16 May '14, 20:24

accept rate: 100%

edited 18 May '14, 18:22

It was some sort of loading problem. Found solution here.

Am able to force model loading with this snippet before the admin autodiscover function in urls.py:

from django.db.models.loading import cache as model_cache
if not model_cache.loaded:

Thanks to all who tried to help me troubleshoot. I always learn something.

permanent link

answered 20 May '14, 00:16

accept rate: 100%

Set the ADMINS e-mail addresses and make sure outgoing e-mail is configured right, this way you will be e-mailed the errors when debug is off.

permanent link

answered 17 May '14, 00:16

accept rate: 23%

I'm already getting the traceback via e-mail. Like I say, it points to a problem with one of my models. It looks like it isn't loading (FieldError: Can't resolve keyword 'game' into field. Choices are...). What doesn't make sense to me is why that model seems to load properly with DEBUG=True.

(17 May '14, 04:40) bwareham

Can you post the full track-back? Can you post the model? If not you may conciser sending us a support ticket so we can look directly. If you are already getting a track-back than the reason is somewhere within it.

(17 May '14, 23:42) johns

Traceback and model added.

(18 May '14, 04:16) bwareham

Where is 'game' coming from exactly, can you explain a bit more about the list choices and what 'game' might mean in the context of the last line of the trackback? Have you tried using DjangoDebugToolbar and maybe The JavaScript console (if you are using JavaScript for this form) to get more info from the DOM to find out where 'game' is coming from, why it is being set, and/or why it should be missing from the list of possible options?

(18 May '14, 04:48) johns

I added some app structure info to the original post. The app is for managing a company softball team - scheduling games, keeping track of players over many seasons, posting team photos, etc.

(18 May '14, 18:24) bwareham

Thanks for the background info however it still does not show what 'game' is exactly in that context. All the code I see has 'Game' (notice the capitol G) since python is dependant on caps it is a different object. In order to debug the FieldError we need to know exactly what 'game' is in this context, what kind of object it is, why/where it is being created, if it is normal for it to be handed off or if it does not belong there at all, etc. Once thing I notice about the trackback is that it does not report any of your code among the py files which are failing, only Django files. Which is likely why it does not show when debug is different. The failure is high up in Django's stack, before the debug mechanism can load. Of course it is likely being triggered by 'high level'(higher up in the Django stack, closer to python's core) code parsing your low level code. If it is any condolence this has happened to me in the past and it can take a while to debug, and seem to make no sense until you find the issue, but in retrospect it typically makes sense. If you can isolate exactly what 'game' is, what kind of python object it is, where it is generated, and why it is being generated, than we can figure out why the FieldError is mentioning it and what to look at next.

(19 May '14, 03:29) johns

The only 'game' presently in my code is the 'Game' (upper case 'G') class you see above. Originally, I did have a 'game' (lower case) fk field in the Stat class, but changed it to simply 'g', and modified the database accordingly. That seemed to take care of a similar FieldError that was affecting the public site, but it didn't fix the problem in the admin. I'm assuming (and, of course, could be wrong) that the lower case field search is occurring because when Django creates db tables it derives a lowercase version of the class name - in this case creating a table called 'gamemaker_game', which indeed is part of my db. Incidentally, the process of creating that model relationship chart made me realize that the field choices are all fields of the Player class or fields of classes that have a fk or M2M relationship back to Player. The glaring exception missing from the choices is the Stat class, which has a fk to Player (and Game). I'm not sure yet how that info helps me, but seems like it might be relevant.

(19 May '14, 16:31) bwareham
showing 5 of 7 show 2 more comments

After I read your post, I changed settings.DEBUG = False in my Django app, and I also got a 500 Internal Error. Although my problem is totally unrelated to your problem, a careful check of my app's log file showed that I needed a change in my settings file to add:


Now my Django app works OK with DEBUG = False. Of course I realize that my problem is totally different than yours, but it would probably be worthwhile for you to carefully comb through your ~/logs/user/error_{app}.log file for clues.

permanent link

answered 18 May '14, 04:54

accept rate: 0%

The only error in the app's error log appears to be unrelated to the FieldError:

[Sun May 18 15:43:02 2014] [notice] caught SIGTERM, shutting down

[Sun May 18 15:43:07 2014] [warn] mod_wsgi: Compiled for Python/2.7.3.

[Sun May 18 15:43:07 2014] [warn] mod_wsgi: Runtime using Python/2.7.5.

[Sun May 18 15:43:07 2014] [notice] Apache/2.2.17 (Unix) mod_wsgi/3.4 Python/2.7.5 configured -- resuming normal operations

(18 May '14, 15:46) bwareham
Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Question tags:


question asked: 16 May '14, 20:24

question was seen: 4,405 times

last updated: 20 May '14, 00:16