【问题标题】:Having admin inline for model without direct relation or foreign key没有直接关系或外键的模型具有管理员内联
【发布时间】:2017-01-19 11:46:53
【问题描述】:

所以,我有这个模型:

class Media(models.Model):
    title = models.CharField(max_length=50, blank=True)
    slug = models.SlugField(max_length=70, blank=True, editable=False)

    class Meta:
        abstract = True

class Photo(Media):
    source = models.ImageField(upload_to='uploads/gallery/photo')

class Video(Media):
    source = models.FileField(upload_to='uploads/gallery/photo')

class Item(models.Model):
    content_type = models.ForeignKey(
        ContentType,
        limit_choices_to={'model__in': ['photo', ]},
        on_delete=models.CASCADE,
    )
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

class Album(Media):
    items = models.ManyToManyField(Item)

如何让相册管理员将照片和视频内联,以便在创建相册时上传照片和视频?

当我尝试为照片内联并将其连接到相册管理员时,我收到错误“照片没有相册的外键”,很明显,从那里我认为应该有一种方法可以将相册管理员所需的外键与内容链接来自模型项的对象。

注意:我特别不想要项目管理员。项目在模型后保存信号处创建。

【问题讨论】:

    标签: python django django-models django-admin


    【解决方案1】:

    我认为这不是开箱即用的。但是您可以使用诸如django-smart-selects-generics 之类的库。根据您的 django 版本,您可能需要在那里更新一些文件。

    安装适用于:

    pip install django-smart-selects-generic
    

    您还需要安装django-smart-selects

    然后在设置中添加这两个应用程序。

    INSTALLED_APPS = (
            ...
            'smart_selects',
            'smart_generic'  
              )
    

    然后在你的 admin.py 中你可以这样做:

    from smart_generic.form_fields import GenericChainedModelChoiceField
    from django.forms.models import ModelForm
    
    class TForm(ModelForm):
        object_id = GenericChainedModelChoiceField('content_type','content_type',label=u'Content object',queryset=TargetRelation.objects.all())
        class Meta:
            model = TargetRelation
            fields = ['target','content_type']
    
    
    class TRAdmin(admin.ModelAdmin):
        form = TForm
    
    class TRInline(admin.TabularInline):
        model = TargetRelation
        form = TForm
    
    class PlanetAdmin(admin.ModelAdmin):
        inlines=[TRInline,]
    

    根据您的 django 版本,您可能需要在 widgets.py 中替换:

    Media = ChainedSelect.Media 
    

    通过

    .media = ChainedSelect.Media 
    

    并在 smart_select views.py 中添加:

    import json as simplejson
    

    并将return语句替换为:

    return HttpResponse(json, content_type='application/json')
    

    【讨论】:

    • 我看到了 repo,但我不知道它在做什么。也没有文档。我只看到表单、小部件和视图。
    猜你喜欢
    • 2017-11-22
    • 2018-10-09
    • 2011-08-10
    • 1970-01-01
    • 2011-06-12
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多