Django-Admin中的ForeignKey字段初始值定义 [英] Django - ForeignKey field initial value definition in Admin
问题描述
我有一个 Person
模型,该模型本身具有一个 ForeignKey
字段,称为母亲
。
当用户转到添加管理表单时,我想为母亲
定义一个初始值,以防万一 GET('mother')
参数,如果没有,则将其留空。
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.
我实际上有2个问题:
- 如何在
ModelAdmin
内访问请求? - 如何为
ForeignKey
字段定义初始值?
- How to access request inside
ModelAdmin
? - How to define initial value for a
ForeignKey
field?
在models.py中:
In models.py:
class Person(models.Model):
name=models.CharField()
mother=models.ForeignKey('self')
在admin.py中:
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.
我在做什么错了?
PS:当然,我可能会问错问题,因此,感谢您解决该问题的任何帮助。
PS.: Of course, I may be asking the wrong questions, so I appreciate any help that solves the problem.
推荐答案
我的解决方案:
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
这篇关于Django-Admin中的ForeignKey字段初始值定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!