django,管理模板错误渲染时捕获异常:'NoneType'对象没有属性'label'

时间:2010-02-23 16:07:02

标签: python django-models django-admin django-templates

好日子的家伙们! 在项目中,有其他模型:

class Category(models.Model):

    name = models.CharField(max_length = 50, blank = False, null = False)

    def __unicode__(self):
        return "Category %s" % self.name

    class Meta:
        db_table = "categories"
        managed = False


class Site(models.Model):

    user = models.ForeignKey(User, blank = False, null = False, db_column = "user_id")
    name = models.URLField(verify_exists = True, blank = False, null = False)
    categories = models.ManyToManyField(Category, blank = True, through = "CategorySites", verbose_name = "Category")

    def __unicode__(self):
        return self.name

    class Meta:
        db_table = "sites"
        managed = False



class CategorySites(models.Model):

    site = models.ForeignKey(Site, blank = False, null = False, db_column = "site_id")
    category = models.ForeignKey(Category, blank = False, null = False, db_column = "category_id")

    def __unicode__(self):
        return "Relation between site %s and category %s" % (self.site.name, self.category.name)

    class Meta:
        db_table = "categories_sites"
        managed = False

所以,如你所见,存在多对多的关系。通常它运作良好 - 我可以通过manage.py shell或服务器端函数添加和管理模型。 我想在管理站点上启用编辑这种类型的关系,因此,我添加了站点的管理模型:

 class SiteAdmin(admin.ModelAdmin):

    list_display = ('id', 'name')
    list_filter = ('name', 'categories')

    fieldsets = (
        (None, {"fields": ("categories",)}),
    )

    def queryset(self, request):
        qs = super(SiteAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs
        else:
            return qs.filter(user = request.user)

    def has_change_permission(self, request, obj=None):
        if not obj:
            return True # So they can see the change list page
        if request.user.is_superuser or obj.user == request.user:
            return True
        else:
            return False

    has_delete_permission = has_change_permission

但是当我进入admin-> sites->添加网站(或编辑)django throws在渲染时捕获异常:'NoneType'对象没有属性'label'。 怎么能修好呢?

1 个答案:

答案 0 :(得分:1)

为此,您需要将未记录的formfield_for_manytomany方法添加到SiteAdmin类:

from django.contrib.admin import widgets

class SitebAdmin(admin.ModelAdmin):

   list_display = ('id', 'name')
   list_filter = ('name', 'categories')

   def formfield_for_manytomany(self, db_field, request, **kwargs):
      if db_field.name == 'categories':
         kwargs['widget'] = widgets.FilteredSelectMultiple(
              db_field.verbose_name, (db_field.name in self.filter_vertical))
      return super(SitebAdmin, self).formfield_for_foreignkey(
         db_field, request, **kwargs)

   fieldsets = (
       (None, {
            "fields": ("name", "categories",)
       }),
   )

覆盖默认情况下不为显示指定了docs的直通选项的模型显示多个选择窗口小部件。

虽然这有效,但我仍然认为这不会导致Django出错。