我正在开发一个Django 1.10项目,其中我有一个名为TaggedArticle的模型,该模型与具有相关名称的用户相关,标记为"现在我想显示一个表格当我们在Django admin中打开用户对象时,TaggedArticle对象。如何在Django Admin中实现该功能?
以下是我的模特: 的 TaggedArticle:
class TaggedArticle(models.Model):
user = models.ForeignKey(User, related_name='tagging')
email = models.EmailField(max_length=255)
category_fit = models.CharField(choices=choices, max_length=255)
article = models.ForeignKey(Article, related_name='articles')
link = models.URLField(max_length=255,)
relevant_feedback = models.TextField(blank=True)
category = models.CharField(max_length=255,)
created_at = models.DateTimeField(default=timezone.now, editable=False)
更新:admin.py
from django.contrib import admin
from .models import TaggedArticle as Tagged
from django.contrib.auth.admin import UserAdmin
from .models import TaggedArticle
from django.contrib.auth import get_user_model
User = get_user_model()
admin.site.unregister(User)
class InlineTaggedArticle(admin.TabularInline):
model = TaggedArticle
class CustomAdmin(UserAdmin):
date_hierarchy = 'date_joined'
inlines = [InlineTaggedArticle, ]
list_display = list(UserAdmin.list_display) + ['totol_tagged_article']
def totol_tagged_article(self, obj):
return obj.tagging.all().count()
admin.site.register(User, CustomAdmin)
class TaggedArticleAdmin(admin.ModelAdmin):
date_hierarchy = 'created_at'
fields = ['category_fit', 'article', 'link', 'relevant_feedback', 'category', 'user', 'email']
list_display = ['article', 'link', 'user', 'email', 'relevant_feedback']
list_filter = ['user', 'email']
model = Tagged
admin.site.register(Tagged, TaggedArticleAdmin)
更新:以下是截图:
答案 0 :(得分:2)
from django.contrib.auth.admin import UserAdmin
from .models import TaggedArticle
from django.contrib.auth import get_user_model
User = get_user_model()
admin.site.unregister(User)
class InlineTaggedArticle(admin.TabularInline):
model = TaggedArticle
class CustomAdmin(UserAdmin):
inlines = [InlineTaggedArticle,]
list_display = list(UserAdmin.list_display) + ['totol_tagged_article']
def totol_tagged_article(self, obj):
return obj.tagging.all().count()
admin.site.register(User, CustomAdmin)
现在,您将在Django admin
中的用户详细信息页面中看到TaggedArticle
表
答案 1 :(得分:1)
你可以在admin.py
中这样写from django.contrib import admin
# Register your models here.
from .models import TaggedArticle
class UserProfileAdmin(admin.ModelAdmin):
list_display = ['']
admin.site.register(TaggedArticle,TaggedArticleAdmin)