django admin: How to customize one field in fieldsets?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-30 21:18:37

Would it work to apply the filter at the model level? If so you can use the limit_choices_to attribute on the model's ForeignKeyField.

Alternatively you could override the formfield_for_foreignkey attribute of the modelAdmin class.

Something like -

class YourModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "ports_with_same_scanner":
            kwargs["queryset"] = PortList.objects.filter(scanner=self.scanner)
        return super(YourModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

(Apologies if I've misunderstood the question)

I don't know if real problem at past ... I always using simple approach - to adding a name of method to the readonly_fields = ()

Example:

models.py

class My(models.Model):

    def custom_name(self):
        return 'test'
    custom_name.allow_tags = False
    custom_name.short_description = 'custom_name'

admin.py

class MyAdmin(admin.ModelAdmin):
    fieldsets = (
            (None, {
                    'fields': ('custom_name', )
            }),
    )
    readonly_fields = ('custom_name', )

It must be working Django >=1.7 It seems the approach can be apply to early version of Django^ but I don't testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!