All models and views and forms are simplified for reading… I will add more code if I removed to mutch
Models:
class PhoneNumber(Context):
telephoneNumber = models.CharField(_('telephonenumber'), max_length=22)
class Entity(models.Model):
addresses = models.ManyToManyField( to=Address
, related_name="address_entity_set"
, blank=True )
websites = models.ManyToManyField(to=Website
, related_name="website_entity_set"
, blank=True)
telephoneNumbers = models.ManyToManyField( to=PhoneNumber
,related_name="phonenumber_entity_set"
)
emails = models.ManyToManyField(to=Email
, related_name="emails_entity_set"
, blank=True)
class Person(Entity):
#I will add code if needed
class Organisation(Entity):
#I will add code if needed
Views:
class PersonCreateView(CreateView):
model = Person
template_name = "person_form_extended.html"
form_class = PersonModelForm
success_url = reverse_lazy('person-list')
Forms:
class PhoneNumberModelForm(ContextModelForm):
prefix="phone"
phone_validator = RegexValidator("^((\+)?[1-9]{1,2})?([-\s\.])?((\(\d{1,4}\))|\d{1,4})(([-\s\.])?[0-9]{1,12}){1,2}$", _('This phone number is invallid'))
telephoneNumber = forms.CharField(
validators = [phone_validator],
widget = forms.TextInput(attrs=
{
"placeholder": "phonenumber",
"type": "tel",
"size": 40, # width in characters
"maxLength": PhoneNumber._meta.get_field('telephoneNumber').max_length,
}
))
class EntityModelForm(ModelForm):
telephoneNumbers = forms.ModelMultipleChoiceField(
queryset = PhoneNumber.objects.all(),
widget = forms.CheckboxSelectMultiple(attrs=
{
}
),
)
#same for other fields
class PersonModelForm(EntityModelForm):
pass
Problem
All separate parts function perfectly. But I want to be able to create a person with the telephone numbers, addresses, email addresses and websites in one form. But when I added:
PhoneNumberFormSet = inlineformset_factory(
Entity, PhoneNumber,
#fk_name="phonenumber_entity_set",
#form=PhoneNumberModelForm,
fields=['telephonenumber'],
extra=1,
can_delete=True
)
I get:
ValueError: ‘MyNetwork.PhoneNumber’ has more than one ForeignKey to ‘MyNetwork.Entity’. You must specify a ‘fk_name’ attribute
and using
fk_name="phonenumber_entity_set",
fails too with: ValueError: 'MyNetwork.PhoneNumber' has no field named 'phonenumber_entity_set'.
I have looked at
*Django inline formsets with Class-based views and crispy forms
*Multiple Models to one Form and all the links mentioned there
*Creating forms in Django with multiple Many-to-Many fields in Models
and many more but I seem to have a readers block and the more I read the less I seem to understand.
I hope someone can help me solve this.
Wouter