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.
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:
Then, I added
ADMIN.PY
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 mychage_view
asextra_context
so I can call it on the template as{{ osm_data.link }}