0

我是 Django 新手,无法理解如何在ModelAdmin. 如果我在上面/admin/mt_app/my_model/我有用户名之类的信息,或者我在上面/admin/auth/user/2/change/有所有用户的信息,我如何在 ModelAdmin 视图中调用这些变量?

我通过插入自己的用户来选择性地工作,但我不知道如何从视图中调用相关用户或模型。我能找到的只是如何调用当前用户,但同样,我需要该页面所涉及的用户,而不是活动用户。例如:/admin/algorx/pt_data/41/change//admin/auth/user/2/change/

我现在拥有的是:

管理员.py

class pt_dataAdmin(admin.ModelAdmin):

    fieldsets = (
       . . .
    )

 # This gets passed into change_view as extra context
    def get_dynamic_info(self):
        user = User.objects.get(email='MYSUPERUSEREMAIL')
        return user
        . . .
    
    def change_view(self, request, object_id, form_url='', extra_context=None):
        . . .

所以有效的是传递我的超级用户的电子邮件来选择该用户:

        user = User.objects.get(email='MYSUPERUSEREMAIL')
        return user

但我想要做的是选择正在查看的当前页面的用户。如果我在以下 URL 上,如何选择该用户的变量? /admin/auth/user/2/change/

我看到很多关于选择当前用户的问题,但我想知道如何选择正在查看的用户。任何帮助将不胜感激,这对我的新手来说已经是 2 天的障碍。

4

1 回答 1

0

After spending two days in stackoverflow hell, I pieced together the answer!

First, I added a field to my model that contains the user who created it:

MODELS.PY:

pt_user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE)

Then, I added

ADMIN.PY

@admin.register(pt_data)
class pt_dataAdmin(admin.ModelAdmin):

    fieldsets = (
         . . . )

    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra_context = extra_context or {}
        pt_model = pt_data.objects.get(id=object_id)
        user = pt_model.pt_user
        loglink = get_query_string(user)
        extra_context['osm_data'] = {'link': loglink}
        # extra_context['osm_data'] = self.get_dynamic_info()
        return super(pt_dataAdmin, self).change_view(
            request, object_id, form_url, extra_context=extra_context,
        )

This let me query the object_id of the URL to find the model in the database, then from the model extract the user. The get_query_string is from a package called Sesame that creates a magic login link for users to login without a password. I return this to my chage_view as extra_context so I can call it on the template as {{ osm_data.link }}

于 2020-10-05T01:32:03.717 回答