开发者

Django Admin Complains About A Missing Field Even When It's Not Missing

  • Python 2.7
  • Django 1.3

When I include 'user_id','user' in the admin.py, then...

  • no user field shows up in the form when I click to add a Timeslip.
  • If I submit it anyway, then it shows the user field with a "This field is required." error message.
  • If I pick a user & submit again, then I get "'TimeslipAdmin.fields' refers to field 'user_id' that is missing from the form." even though 'user_id' is clearly listed in my admin.py (see below)

The Traceback says --

  • Exception Type: ImproperlyConfigured at /admin/timeslip/timeslip/add/
  • Exception Value: 'TimeslipAdmin.fields' refers to field 'user_id' that is missing from the form.

But...if I leave 'user_id','user' out of the admin.py then....

  • no user field shows up when I click to add a Timeslip.
  • Submit it anyway, and it shows the user field & a "Timeslip with this User already exists." error message开发者_运维技巧. (which shouldn't be an error either 'cause I want users to have multiple Timeslip's which means another error I'll have to figure out once I can just get this form working)

admin.py

from timeslip.models import Timeslip
from django.contrib import admin

class TimeslipAdmin(admin.ModelAdmin):
    fields = ['user_id','user','day','hours_as_sec','part_of_day','drove','gas_money','notes']

admin.site.register(Timeslip, TimeslipAdmin)

models.py

from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class Timeslip(models.Model):
   user=models.ForeignKey(User)
   day = models.DateField()
   hours_as_sec = models.PositiveIntegerField()
   part_of_day = models.CharField(max_length=16,choices=PART_O_DAY)
   drove = models.BooleanField(default=False)
   gas_money = models.DecimalField(max_digits=5,decimal_places=2)
   notes = models.TextField()

class UserProfile(models.Model):
   user = models.ForeignKey(User)
   url = models.URLField("Website", blank=True)
   position = models.CharField(max_length=50, blank=True)

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

I'm very clueless how to overcome this. I'm coming from a PHP background, a newbie to Python & Django.


user_id and user are redundant. Django automatically names your user field user_id in the database (since it holds the id for the User instance it points to.)

Change your admin.py to the following and it should work:

class TimeslipAdmin(admin.ModelAdmin):
    fields = ['user','day','hours_as_sec','part_of_day','drove','gas_money','notes']

Also you're including all of the fields in the admin, so you really don't need to specify the fields. This would work just as well:

class TimeslipAdmin(admin.ModelAdmin):
    pass


But...if I leave 'user_id','user' out of the admin.py then...

You haven't got 'user_id' field. So delete only this field and I think everything will work fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜