Django - inline form for OneToOne field in admin site

Hey. This question has been asked many times, but, unfortunately, I could not find an answer to it that would really work. Below are my models:

class Person(models.Model): name = models.CharField(max_length=100) ... class Address(models.Model): person = models.OneToOneField(Person) ... 

Then in admin I have:

 class AddressInline(admin.StackedInline): model = Address class PersonAdmin(admin.ModelAdmin): inlines = (AddressInline) admin.site.register(Person, PersonAdmin) 

and then I get this shameful error:

 <class 'address.models.Address'> has no ForeignKey to <class 'person.models.Person'> 

I tried:

  • Django is a reverse administrator. Unfortunately, I did not work with Django 1.6, and I am not sure enough that it would work with 1.6.
  • A few suggestions in the stack thread when using proxy models and an abstract base class, and they didn't work either.

I would really appreciate if someone would help me find a workaround for him.

+6
source share
2 answers

I have not tried, but this method is based on code in django-reverse-admin, but updated to work with Django 1.6:

https://gist.github.com/mzbyszewska/8b6afc312b024832aa85

Note that this part of the sample code is incorrect:

 class AddressForm(models.Form): pass 

... you need from django import forms at the top, and then do something like:

 class AddressForm(forms.ModelForm): class Meta: model = Address 

Another problem in the sample code here is line # 46:

 inline_reverse = ('business_addr', ('home_addr', AddressForm), ('other_addr' ( 'form': OtherForm 'exclude': () ))) 

should be:

 inline_reverse = ('business_addr', ('home_addr', AddressForm), ('other_addr', { 'form': OtherForm, 'exclude': () })) 

note that it shows you three different ways to specify the built-in ... the first is just the name of the 'business_addr' ie field if you do not need a custom form for the built-in model.

+10
source

I have installed:

  • Django == 1.6.5
  • MySQL python == 1.2.4
  • South == 0.8.1

and the code below works with me:

models.py

 # -*- coding: utf-8 -*- from django.db import models class Person(models.Model): name = models.CharField(max_length=100) class Address(models.Model): person = models.OneToOneField(Person) street = models.CharField(max_length=100) 

admin.py

 # -*- coding: utf-8 -*- from django.contrib import admin from .models import * class AddressInline(admin.StackedInline): model = Address class PersonAdmin(admin.ModelAdmin): inlines = (AddressInline,) admin.site.register(Person, PersonAdmin) admin.site.register(Address) 

And these are the admins:

admin interface

+3
source

Source: https://habr.com/ru/post/971896/


All Articles