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

后端 未结 7 956
爱一瞬间的悲伤
爱一瞬间的悲伤 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:08

    A more general approach could be writing an helper method to obtain the model instance (if any), much as you normally do with a (bounded) ModelForm, and from that retrieve the id or any other property:

    from django.contrib import admin
    
    class MyModelAdmin(admin.ModelAdmin):
    
        def get_instance(self, request):
            try:
                object_id = request.resolver_match.kwargs['object_id']
                obj = self.get_object(request, object_id)
            except:
                obj = None
            return obj
    

提交回复
热议问题