I 've already solved the problem of getting the object id being edited using this code:
class CompanyUserInline(admin.StackedInline):
"""
Defines tabular rules for editing company users direct in company admin
"""
model = CompanyUser
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "user":
users = User.objects.filter( Q(is_superuser=False) )
query = Q()
for u in users:
aux = CompanyUser.objects.filter(user=u)
if aux.count() == 0:
query |= Q(pk=u.id)
try:
cpu = CompanyUser.objects.filter(company__id=int(request.path.split('/')[4]))
for p in cpu:
query |= Q(pk=p.user.id)
except:
pass
kwargs["queryset"] = User.objects.filter(query).order_by('username')
return super(CompanyUserInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
But, the int(request.path.split('/')[4]) is really ugly. I want to know how I get the id from the Django AdminModel. I'm sure it's somewhere inside it, anyone knows?
Thank you in advance! ;D
I was dealing with a similar situation, and realized that the id that that I needed from the request, I could from from the model it self since it was a foreign key to that model. So it would be something like:
or what ever the structure of your model dictates.
I made it work by creating a property() in model.py that returns the ID
models.py:
admin.py:
As far as i know it is not possible to access the current instance through the
formfield_for_...
-methods, because they will only be called for a single field instance!A better point to hook into this logic where you can access the whole instance/form would be
get_form
. You can also overwrite a form field's queryset there!I made it work by rewrite
change_view()
then you can call
self.object_id
insideformfield_for_foreignkey()
The following code snippet will give you the object id:
Sample usage: (I'm filtering the phone numbers shown, to only show customer's phone numbers)
P.S: Found it by debugging and walking through accessible variables.
After some digging around, we were able to grab the arguments that get passed to the admin view (after being parsed by django admin's urls.py) and use that (self_pub_id) to grab the object:
A more elegant solution is to use the accepted answers recomendation and leverage the get_form ModelAdmin member function. Like so: