【问题标题】:Django validation of generic relation from a GenericInlineModelAdmin来自 GenericInlineModelAdmin 的泛型关系的 Django 验证
【发布时间】:2013-06-05 15:55:01
【问题描述】:

我正在尝试验证从 GenericInlineModelAdmin 表单保存的通用关系对象。

创建对象时,object_idcontent_type 设置为 None,我无法访问它的相关对象,但当对象更新时,它们已正确设置。

这里是示例代码:

models.py:

class Article(models.Model):
    title = models.CharField(max_length=32)
    body = models.TextField()

class TaggedItem(models.Model):
    tag = models.SlugField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    def clean(self, exclude=None):
        pass

admin.py:

class InlineTags(generic.GenericTabularInline):
    model = TaggedItem

class ArticleAdmin(admin.ModelAdmin):
    inlines = [InlineTags]

admin.site.register(Article, ArticleAdmin)

如果添加标签,在TaggedItem.clean() 方法中self.object_idself.content_type 设置为None。如果正在编辑标签,则它们已正确设置。

我在 django 1.4.x 和 1.5.x 上都试过这个。

【问题讨论】:

    标签: django django-models django-forms django-admin


    【解决方案1】:

    这似乎是 Django 中一个未解决的错误(问题 #19255)。

    我尚未对其进行测试,但由于您将标签保存在管理员中,您可以通过添加自定义 ModelForm 来解决此问题,如下所示:

    class InlineTagsForm(forms.ModelForm):
        def clean(self):
            """ Validate object_id & content_type fields """
            assert self.cleaned_data.get('object_id')
            assert self.cleaned_data.get('content_type')
            return self.cleaned_data
    
    
    class InlineTags(generic.GenericTabularInline):
        model = TaggedItem
        form = InlineTagsForm
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-29
      • 2012-03-20
      • 2011-01-17
      • 1970-01-01
      • 2015-12-05
      • 2011-04-17
      • 2013-10-22
      • 1970-01-01
      相关资源
      最近更新 更多