Django - 管理站点中OneToOne字段的内联表单 [英] Django - Inline form for OneToOne field in admin site
问题描述
这个问题已经被问了很多次,但不幸的是,我找不到一个实际可行的答案。以下是我的模型:
Hi This question has been asked many times but unfortunately I could not find an answer for it that would actually work. Below are my models:
class Person(models.Model):
name = models.CharField(max_length=100)
...
class Address(models.Model):
person = models.OneToOneField(Person)
...
然后在管理员中我有:
class AddressInline(admin.StackedInline):
model = Address
class PersonAdmin(admin.ModelAdmin):
inlines = (AddressInline)
admin.site.register(Person, PersonAdmin)
然后我得到这个臭名昭着的错误:
and then i get this infamous error:
<class 'address.models.Address'> has no ForeignKey to <class 'person.models.Person'>
我尝试过:
- django-reverse-admin。不幸的是没有使用Django 1.6,而且我没有足够的空间使其能够与1.6一起工作。
- 在使用代理模型和抽象基类并且没有工作的情况下,stackoverflow中有几个提示。
如果有人可以帮助我找到解决方法,我真的很感激。
I would really appreciate if someone could help me to find a workaround for it.
推荐答案
我没有尝试过,但这个要点似乎是基于django-reverse-admin中的代码,但更新为在Django 1.6上工作:
I have not tried it, but this gist appears to be based on the code in django-reverse-admin but updated to work on Django 1.6:
https://gist.github.com/mzbyszewska/8b6afc312b024832aa85
请注意,这部分示例代码是错误的:
Note that this part of the example code is wrong:
class AddressForm(models.Form):
pass
...您需要从django导入表单
在顶部,然后执行以下操作:
...you need to from django import forms
at the top and then do something like:
class AddressForm(forms.ModelForm):
class Meta:
model = Address
这里的第46行示例代码中还有另一个问题:
There's another problem in the example code here line #46:
inline_reverse = ('business_addr', ('home_addr', AddressForm), ('other_addr' (
'form': OtherForm
'exclude': ()
)))
应该可能是:
inline_reverse = ('business_addr', ('home_addr', AddressForm), ('other_addr', {
'form': OtherForm,
'exclude': ()
}))
注意,它显示了三种不同的方式来指定内联...第一个只是通过字段名称'business_addr'
即如果你不需要内嵌模式的自定义表单。
note that it shows you the three different ways to specify an inline... the first is just by field name 'business_addr'
i.e. if you don't need a custom form for the inline model.
这篇关于Django - 管理站点中OneToOne字段的内联表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!