如何使用管理面板中的动态数据? [英] How to work with dynamic data in Admin Panel?

查看:142
本文介绍了如何使用管理面板中的动态数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ _ code> class Message(models.Model):

date = models.DateField()
user = models.ForeignKey(UserEx)
groups = models.ManyToManyField(Group)
main_category = models.ForeignKey(MainCategories)
sub_category = models.ForeignKey(SubCategories)

我想要动态填充一些字段。所以,我有一些问题。


  1. 如何访问此字段?显然,
    模型的默认字段将无法与动态数据一起使用(我试图装箱默认字段 - 没有错误,没有结果)。

  2. 如何过滤组?我的用户与组具有相同的字段,所以我想允许他编辑和显示只有这些组的消息。

和最后一个问题 - 也许更容易创建我自己的管理面板?但是,在管理面板中,考虑实现排序和显示的东西,这真的很舒服,真的很可怕。

解决方案

你通过覆盖ModelForm来实现:

  class MessageAdminForm(forms.ModelForm):
def __init __(self,* arg ,** kwargs):
super(MessageAdminForm,self).__ init __(* args,** kwargs)

#以这种方式设置初始值
self.initial ['user '] = User.objects.get(username ='bob')

#以这种方式设置选项
self.fields ['groups']。choices = [(g.id,g )for g in Groups.objects.all()]

class MessageAdmin(admin.ModelAdmin):
form = MessageAdminForm
#其他内容


class Message(models.Model):

    date = models.DateField()
    user = models.ForeignKey(UserEx)
    groups = models.ManyToManyField(Group)
    main_category = models.ForeignKey(MainCategories)
    sub_category = models.ForeignKey(SubCategories)

I want dynamic filling of some of the fields. So, I've got some questions about it.

  1. How to get access to this fields? Obviously, default field of the model won't work with dynamic data (I tried to crate default field - no errors, no result).
  2. How to filter groups? My user has the same field with groups, so I want allow him to edit and display messages only for that groups only.

Well, and last one question - maybe it'll be more easy to create my own admin panel? But it's really scary to think about realisation of sorting and displaying things, that are really comfort here, in admin panel.

解决方案

You do that by overriding the ModelForm:

class MessageAdminForm(forms.ModelForm):
    def __init__(self, *arg, **kwargs):
        super(MessageAdminForm, self).__init__(*args, **kwargs)

        # set initial values this way
        self.initial['user'] = User.objects.get(username='bob')

        # set choices this way
        self.fields['groups'].choices = [(g.id, g) for g in Groups.objects.all()]

class MessageAdmin(admin.ModelAdmin):
    form = MessageAdminForm
    # other stuff here

这篇关于如何使用管理面板中的动态数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆