你好我试图从两个模型更新多对多字段。我可以从群集模型成功更新具有M2M字段的模型,但我无法从子网模型更新它。
我将在子网的模板表单中获得的是群集列表... buuuut
现在我想我只能从群集方面更新m2m关系,当我说出来时我会是正确的吗?
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输出
<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>
答案 0 :(得分:0)
这似乎与以下内容重复:
Django ModelForm for Many-to-Many fields
第一个答案不会改变模型,并向您展示如何使您的init复杂化并保存方法以使您的模型工作。
第二个答案是通过模型明确定义自己的m2m来简化表单。