Django - ForeignKey field initial value definition in Admin

◇◆丶佛笑我妖孽 提交于 2020-01-02 06:16:48

问题


I have a Person model, which has a ForeignKey field to itself, called mother. When the user goes to the 'add' admin form, I want to define an initial value for mother, in case there is a GET('mother') parameter, or leave it blank, in case there is not.

I have actually 2 questions:

  1. How to access request inside ModelAdmin?
  2. How to define initial value for a ForeignKey field?

In models.py:

class Person(models.Model):
    name=models.CharField()
    mother=models.ForeignKey('self')

In admin.py:

class  PersonAdminForm(forms.ModelForm):
    class Meta:
        model = Person

class PersonAdmin(admin.ModelAdmin):
    mother = request.GET.get('mother','') #don`t know how to access request

    if mother != '':
        form = PersonAdminForm
        form.initial={'mother':Person.objects.get(id=mother)}

Well, this ain't working. Even if I only try to define a hardcoded initial value, it doesn`t work.

What am I doing wrong?

PS.: Of course, I may be asking the wrong questions, so I appreciate any help that solves the problem.


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/12656529/django-foreignkey-field-initial-value-definition-in-admin

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