How do I get the actual object id in a Django admin page (inside formfield_for_foreignkey)?

后端 未结 7 948
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 09:59

I \'ve already solved the problem of getting the object id being edited using this code:

class CompanyUserInline(admin.StackedInline):
    \"\"\"
    Defines         


        
相关标签:
7条回答
  • 2020-12-15 10:32

    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:

    class PublicationAdmin(admin.ModelAdmin):
    
        def formfield_for_manytomany(self, db_field, request, **kwargs):
            if db_field.name == "authors":
                #this line below got the proper primary key for our object of interest
                self_pub_id = request.resolver_match.args[0]
    
                #then we did some stuff you don't care about
                pub = Publication.objects.get(id=self_pub_id)
                kwargs["queryset"] = pub.authors.all()
            return super(PublicationAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
    

    A more elegant solution is to use the accepted answers recomendation and leverage the get_form ModelAdmin member function. Like so:

    class ProfileAdmin(admin.ModelAdmin):
        my_id_for_formfield = None
        def get_form(self, request, obj=None, **kwargs):
            if obj:
                self.my_id_for_formfield = obj.id
            return super(ProfileAdmin, self).get_form(request, obj, **kwargs)
    
        def formfield_for_foreignkey(self, db_field, request, **kwargs):
            if db_field.name == "person":
                kwargs["queryset"] = Person.objects.filter(profile=self.my_id_for_formfield)
            return super(ProfileAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
    
    0 讨论(0)
提交回复
热议问题