使用django admin中的raw_id_fields添加链接到更改页面

时间:2016-03-14 13:56:03

标签: django django-admin

有没有机会在django admin中添加链接到'raw_id_fields'旁边的外键对象的页面? 我使用raw_id_fields来减少对mysql的查询次数。 当我不使用raw_id_fields时,我可以编辑或添加外键对象。

如何使用raw_id_fields进行操作?

@AntoinePinsard,我尝试了第二种解决方案。 “Edit My FK”字段已创建,但除连字符外没有其他内容。

那是我的模式。

class FlatAdmin(admin.ModelAdmin):
    inlines = [NeedInline]
    readonly_fields = ('flat_house_edit_link',)
    raw_id_fields = ('flat_house',)
    list_display = ('show_date','show_block','show_house','show_rooms','show_price','show_stage')
    list_filter = ('flat_house__house_block','flat_rooms')
    search_fields = ('flat_house__id',)

    field = ['flat_house','flat_house_edit_link','flat_owner','flat_price','flat_rooms','flat_total_sq','flat_life_sq','flat_kitchen_sq','flat_floors']

    def flat_house_edit_link(self, instance):
        if instance:
            fk_id = instance.user_id
        else:
            fk_id = None
        if fk_id:
            opts = instance._meta.get_field('flat_house').rel.model._meta
            related_url = reverse(
                'admin:{}_{}_change/?_to_field=id&_popup=1'.format(
                     opts.ha,
                     opts.house,
                ),
                args=[fk_id],
            )
            return format_html(
                 '<a target=_blank href="{}">Go!</a>', related_url)
        else:
            return "No related object"
    flat_house_edit_link.short_description = "Change house"
admin.site.register(Flat,FlatAdmin)

2 个答案:

答案 0 :(得分:6)

  

注意此行为现在为built-in since Django 1.10

您可以创建自定义窗口小部件,以根据需要呈现此字段。

from django.contrib.admin.widgets import ForeignKeyRawIdWidget
from django.core.urlresolvers import reverse, NoReverseMatch
from django.utils.html import format_html

class ForeignKeyLinkedRawIdWidget(ForeignKeyRawIdWidget):
    def render(self, name, value, attrs=None):
        output = super().render(name, value, attrs)
        try:
            related_url = reverse(
                'admin:{}_{}_change'.format(
                    self.rel.model._meta.app_label,
                    self.rel.model._meta.model_name,
                ),
                args=[value],
            )
        except NoReverseMatch:
            return output
        return format_html('{output} <a href="{url}">edit</a>',
                           output=output, url=related_url)

在表单中使用此小部件,而不是使用raw_id_fields

from myapp.forms.widgets import ForeignKeyLinkedRawIdWidget

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = '__all__'
        widgets = {
            'my_foreignkey': ForeignKeyLinkedRawIdWidget(),
        }

class MyModelAdmin(admin.ModelAdmin):
    form = MyForm

然而,将它添加为&#34;假的&#34>会更简单。 readonly_field低于实际字段:

from django.core.urlresolvers import reverse
from django.utils.html import format_html

class MyModelAdmin(admin.ModelAdmin):
    readonly_fields = ['my_foreignkey_link']
    raw_id_fields = ['my_foreignkey']
    fields = [..., 'my_foreignkey', 'my_foreignkey_link', ...]

    def my_foreignkey_link(self, instance):
        if instance:
            fk_id = instance.my_foreignkey_id
        else:
            fk_id = None
        if fk_id:
            opts = instance._meta.get_field('my_foreignkey').rel.model._meta
            related_url = reverse(
                'admin:{}_{}_change'.format(
                     opts.app_label,
                     opts.model_name,
                ),
                args=[fk_id],
            )
            return format_html(
                 '<a target=_blank href="{}">Go!</a>', related_url)
        else:
            return "No related object"
    my_foreignkey_link.short_description = "Edit My FK"

进一步阅读:https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields

答案 1 :(得分:0)

这是一个针对我的代码段页面(已更新6年):

https://djangosnippets.org/snippets/2217/

只需使用ImproveRawIdFieldsForm代替ModelAdmin,所有raw_id字段都会自动链接ID输入旁边显示的对象名称。