How to call user variables in Django ModelAdmin

346 views Asked by At

I am new to Django and having trouble understanding how to call proper variables in a ModelAdmin. If I am on /admin/mt_app/my_model/ that I have information like the user's name OR I'm on /admin/auth/user/2/change/ that has all the user's information, how do I call those variables in the ModelAdmin View?

I got it working selectively by plugging in my own user, but I can't figure out how to call the relevant user or model from the view. All I can find is how to call the current user, but again, I need the user of the that the page is regarding, not the active user. Ex: /admin/algorx/pt_data/41/change/ or /admin/auth/user/2/change/

What I have now is:

Admin.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):
        . . .

So what works is passing in my super user's email to select that user:

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

But what I want to do is select the user of the current page being viewed. If I'm on the following URL how do I select that user's variable? /admin/auth/user/2/change/

I see many SO questions about selecting the current user, but I want to know how to select the user being viewed. Any help would be appreciated, this has now been a 2 day roadblock for my novice-self.

1

There are 1 answers

0
Austin On BEST ANSWER

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 }}