Django - ForeignKey field initial value definition in Admin

≯℡__Kan透↙ 提交于 2019-12-05 14:17:06

My solution:

class PersonAdmin(admin.ModelAdmin):
    form = PersonAdminForm
    # ...
    def get_form(self, request, obj=None, *args, **kwargs):
        form = super(PersonAdmin, self).get_form(request, *args, **kwargs)
        # Initial values
        form.base_fields['mother'].initial = None
        if obj and obj.mother:
            form.base_fields['mother'].initial = obj.mother
        return form

Oh, it happens to be a lot easier than I thought.

If you pass a GET parameter with the name of the field as key to a Django`s add form, the GET parameters value will be set as initial value for that field.

In my case, I just needed to redirect to

localhost/admin/my_app/person/add/?&mother=< id >

There was no need for manipulating admin or anything.

Try overriding the get_form() method on ModelAdmin:

    class PersonAdmin(admin.ModelAdmin):
        form = PersonAdminForm

        def get_form(self, request, *args, **kwargs):
            form = super(PersonAdmin, self).get_form(request, *args, **kwargs)
            mother = request.GET.get('mother', None)
            if mother:
                form.initial = {'mother': Person.objects.get(id=mother)}
            return form
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!