Howdy I am trying to update a Many to Many field from both models. I can successfully update from the Cluster model the one with the M2M field, but I cant update it from the Subnet model.
What I will get in the template form for subnet is a list of clusters... buuuut
- The clusters that are assigned to the subnet are not showing checked
- When I do select a cluster and update the form it does not add the subnet to the cluster
Now im thinking I can only update the m2m relationship from the Cluster side, would I be right when I say that?
models.py
class Cluster(models.Model):
cluster = models.CharField(max_length=130, unique=True)
subnet = models.ManyToManyField('Subnet', null=True, blank=True)
class Subnet(models.Model):
network_address = models.IPAddressField()
subnet_prefix = models.ForeignKey('SubnetPrefix')
forms.py
class SubnetForm(forms.ModelForm):
cluster = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, required=True, queryset=Cluster.objects.all())
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_tag = True
self.helper.layout = Layout(
Div(
Div(Field('network_address', css_class="input-sm"), css_class="col-lg-4"),
Div(Field('subnet_prefix', css_class="input-sm"), css_class="col-lg-2"),
css_class="row"
),
Div(
Div(Field('cluster', css_class="nav nav-list"), css_class="col-lg-4"),
css_class="row"
),
Div(
Div(
Submit('submit', 'Submit'),
),
css_class="row",
),
)
super(SubnetForm, self).__init__(*args, **kwargs)
class Meta:
model = Subnet
views.py
class SubnetUpdateView(UpdateView):
template_name = 'subnet_update.html'
model = Subnet
form_class = SubnetForm
success_url = '#'
def form_valid(self, form):
messages.success(self.request, u"Subnet updated successfully.")
return super(SubnetUpdateView, self).form_valid(form)
subnet_update.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<h1>Update Subnet</h1>
<br />
{% crispy form %}
<br />
{% endblock %}
html output of cluster form
<div class="row" >
<div class="col-lg-4" >
<div id="div_id_cluster" class="form-group">
<label for="id_cluster_0" class="control-label requiredField">Cluster<span class="asteriskField">*</span></label>
<div class="controls " class="nav nav-list">
<label class="checkbox"><input type="checkbox" name="cluster" id="id_cluster_1" value="1" class="nav nav-list">CLUSTER01</label>
<label class="checkbox"><input type="checkbox" name="cluster" id="id_cluster_2" value="2" class="nav nav-list">CLUSTER02</label>
<label class="checkbox"><input type="checkbox" name="cluster" id="id_cluster_3" value="3" class="nav nav-list">CLUSTER03</label>
</div>
</div>
</div>
</div>