在Django Admin中添加用户模型中的用户相关对象

时间:2017-10-14 04:30:34

标签: python django django-models django-admin

我正在开发一个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)
  

更新:以下是截图:

  1. 标签文章列表视图:
  2. enter image description here

    1. TaggedArticle的详情页面:
    2. enter image description here

      1. 用户的详细信息页面:
      2. enter image description here

        在用户的详细信息页面上,应显示TaggedArticle对象中的所有字段 请帮帮我! 在此先感谢!

2 个答案:

答案 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)