我有一个通用的Django媒体模型,我想与其他一些模型相关联。一切似乎工作正常,但我无法使用管理员中的内联表单保存新的或现有的对象。以下是相关模型:
from django.db import models
from franklin.utils.content_media import *
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from franklin.core.scripts.models import Script
class Media(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
media_type = models.CharField(max_length = 20, choices = media_types)
media_file = models.CharField(max_length = 300, blank = True)
text_value = models.CharField(max_length = 2000, blank = True)
caption = models.CharField(max_length = 300, blank = True)
attributes = models.CharField(max_length = 150, blank = True)
related_id = models.PositiveIntegerField(null = True, blank = True)
template = models.ForeignKey(Script, null = True, blank = True)
sort_order = models.IntegerField(default = 1)
class StaticContent(models.Model):
title = models.CharField(max_length = 100, unique = True)
key = models.CharField(max_length = 200, unique = True)
content_type = models.CharField(max_length = 10, choices = content_types)
content = models.TextField(blank = True)
media = generic.GenericRelation(Media, content_type_field='content_type', object_id_field='object_id')
以下是管理员代码:
from django.contrib import admin
from forms import *
from models import *
from django.contrib.contenttypes import generic
class MediaInline(generic.GenericTabularInline):
model = Media
form = MediaFormInline
extra = 1
verbose_name_plural = 'media'
class static_content_admin(admin.ModelAdmin):
inlines = [MediaInline]
admin.site.register(StaticContent, static_content_admin)
以下是令人不快的表格:
from models import *
from django import forms
class MediaFormInline(forms.ModelForm):
class Meta:
model = Media
fields = ('media_type', 'sort_order',)
内联表单显示正确,但保存时出现以下错误:
Django版本:1.3 pre-alpha 异常类型:TypeError 例外值:
'NoneType'对象不可迭代
异常位置:... django的\的contrib \ CONTENTTYPES \ generic.py中的 _ 设置 _ 下,线217
在误差与发生的 _ 设置 _ 一个ReverseGenericRelatedObjectsDescriptor类的方法。该页面将
def __set__(self, instance, value):
if instance is None:
raise AttributeError("Manager must be accessed via instance")
manager = self.__get__(instance)
manager.clear()
for obj in value:
manager.add(obj)
对此的任何帮助将不胜感激。如果我无法解决这个问题,我将不得不采取一种不那么干的解决方案。
答案 0 :(得分:2)
您需要使用GenericTabularInline
。请参阅Django docs。
样品:
from django.contrib.contenttypes.admin import GenericTabularInline
class MediatInline(GenericTabularInline):
model = Media
extra = 1
class StaticContentAdmin(admin.ModelAdmin):
inlines = [MediaInline]