如何在不使用内联的情况下向管理员添加字段?

时间:2016-09-02 00:57:23

标签: django django-admin

基于django-photologue我想让用户拥有自己的图库,并希望在管理员中显示图库的所有者。

Inlines在管理页面底部提供了额外的字段。我只需要一个字段user,我想在管理页面的主要块中显示,即在Gallery模型的其他字段中显示。

# models
from photologue.models import Gallery
from profiles.models import UserProfile

class GalleryExtended(models.Model):
    gallery = models.OneToOneField(Gallery)
    user = models.ForeignKey(UserProfile, verbose_name=_('user'), on_delete=models.CASCADE)

    def __str__(self):
        return self.gallery.title

# admin
from django import forms
from django.contrib import admin
from photologue.admin import GalleryAdmin as GalleryAdminDefault
from photologue.models import Gallery
from .models import GalleryExtended

class InlineGalleryExtendedAdmin(admin.TabularInline):
    model = GalleryExtended

class GalleryAdminForm(forms.ModelForm):
    class Meta:
        model = Gallery
        exclude = ('description', )

class GalleryAdmin(GalleryAdminDefault):
    form = GalleryAdminForm
    save_on_top = True
    inlines = [InlineGalleryExtendedAdmin] # Do not want to use inlines

我尝试添加到class GalleryAdmin

fields = ('user',)  # also tried to add to fieldsets
def user(self, instance):
    return instance.galleryextended.user

但它不起作用。它只适用于list_display,即:

list_display = ('user',)

2 个答案:

答案 0 :(得分:0)

'user'添加到readonly_fields,然后您可以将'user'添加到fileds

https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields

答案 1 :(得分:0)

OneToOneField几乎与所需模型的直接继承相同,所以如果这样做:

# models.py
from photologue.models import Gallery
from profiles.models import UserProfile

# - class GalleryExtended(models.Model):
class GalleryExtended(Galley):
# -    gallery = models.OneToOneField(Gallery)
    user = models.ForeignKey(UserProfile, verbose_name=_('user'), on_delete=models.CASCADE)

# admin.py

from django.contrib import admin

from photologue.admin import GalleryAdmin as GalleryAdminDefault
from photologue.models import Gallery

from .models import GalleryExtended

class GalleryAdmin(GalleryAdminDefault):
    save_on_top = True

admin.site.unregister(Gallery)
admin.site.register(GalleryExtended, GalleryAdmin)

user字段将位于主块内。作为缺点 - 在site.com/admin应用程序的子类别链接移动到其自己的应用程序类别