开发者

django admin - how to override the default <select> view for foreign key?

开发者 https://www.devze.com 2022-12-18 10:59 出处:网络
I have 2 django model class Location address = models.CharField(max_length=100) city = models.CharField(max_length=20)

I have 2 django model

class Location
  address = models.CharField(max_length=100)
  city = models.CharField(max_length=20)

class Client
  location = models.ForeignKey(Location)
  name = models.CharField(max_length=100)

And I have the following admin.py

class ClientAdmin(admin.ModelAdmin):
fieldsets = [
    ('Client Details', {'fields': ['name']}),
    ('Location Details', {'fields': ['location']}),
]


admin.site.register(Client, ClientAdmin)

When I try to add a Client I like to have a editable "location" fields i.e. address and city text fields. django by default gives a list.. how can I get the fields from the foregin tables?

any way I can do this? I don't wish to register the L开发者_开发技巧ocation table in the admin.

thanks


You could put an inline table for the location and use the method queryset to handle the field values. So, this is the ideia of the solution:

class LocationInline(admin.StackedInline):
    model = Location

    def queryset(self, request):
        query = ... #your custom query here
        qs = super(LocationInline, self).queryset(request).filter(query)
        return qs


class ClientAdmin(admin.ModelAdmin):
    inlines = [LocationInline]
    fieldsets = [
        ('Client Details', {'fields': ['name']}),
    ]

Edit: There is another way to do it in django 1.1.

class ClientAdmin(admin.ModelAdmin):
    fieldsets = [
        ('Client Details', {'fields': ['name']}),
        ('Location Details', {'fields': ['location']}),
    ]

def formfield_for_foreignkey(self, db_field, request, **kwargs):

    if db_field.name = "location":
        locations = Location.objects.filter( ... ) #your query

        kwargs["queryset"] = Location.objects.filter(query)

    return super(ClientAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

The docs are here: http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey

It's an old question, but answering this can help a lot of other people too. So, I hope it helps! ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消