Model:
class Address(models.Model):
class Entity(models.Model):
addresses = models.ManyToManyField(to=Address, blank=True, related_name='entity_related_to_address')
class Person(Entity):
pass
So the link I refer here are
Person(Entity) < addresses> → Address
And the reverse link:
Address <entity_related_to_address> → entity
form (simplefied):
class AddressModelForm(ContextModelForm):
entity_related_to_address = forms.ModelMultipleChoiceField(
queryset = Entity.objects.all(),
widget = forms.CheckboxSelectMultiple(attrs=
{ }
),
)
def __init__(self, *args, **kwargs):
super(AddressModelForm, self).__init__(*args, **kwargs)
self.fields['entity_related_to_address'].required = False
All added code to provide a searchfield and some added functionality like ‘forcing the selected fields to the front of the list with (s)css… not relevant here so not shown.
The template for a form with checkbox list:
{% load i18n %}
<div class="data-element-group">
<label for="{{ form.entity_related_to_address.id_for_label }}">{% translate "entity" %}</label>
<fieldset >
<ul id="entityList">
{% for entity in form.entity_related_to_address %}
<li>
<span for="{{ entity.id_for_label }}">
<span class="radio">{{ entity.tag }}</span>
{{ entity.choice_label }}
</span>
</li>
{% endfor %}
<ul>
</fieldset>
<div class="errors"> {{ form.entity_related_to_address.errors }} </div>
<div class="help"> {{ form.entity_related_to_address.help_text }} </div>
</div>
The Person html page shows excisting link to address
and address shows the entity (person in this case) by following the ‘reverse’ link via the ‘related_name’.
(The fuchsia lines are for testing )
The form for person shows the addres list with the correct checked address
But the entity form does not check the correct entity nor does it save any enity I check. This always fails for all implementations using the related_name:
So it works multiple times by following the ‘normal’ link but not the other way around. It does not check the excisting relations and it does not save any checked (new) relation.
How can I check the checkbox that excists as a link in the db and probably related… save it and any new link
bonus: why does this code work one way and not the other way? I presume it has to do with the fact that I follow the reverse link.