选中删除复选框后,提交表单时不会删除LayerMapOptions实例。否则,表单适用于所有其他字段。通过模型的形式有什么特别的事情要做吗?
模型:
class EzMap(models.Model):
map_name = models.SlugField(max_length=50)
layers = models.ManyToManyField(Shapefile, through='LayerMapOptions', verbose_name='Layers to display', null=True, blank=True)
class Shapefile(models.Model):
filename = models.CharField(max_length=255)
class LayerMapOptions(models.Model):
layer = models.ForeignKey(Shapefile)
ezmap = models.ForeignKey(EzMap)
position = models.IntegerField(max_length=100)
visible = models.BooleanField()
视图:
def setMapOptions(request, map_name):
map_selected = EzMap.objects.get(map_name=map_name, created_by=request.user)
layers_ordered = LayerMapOptions.objects.filter(ezmap=map_selected).order_by('position')
layerForm = modelformset_factory(LayerMapOptions, form=LayerMapOptionsForm, extra=0, can_delete=True)
if request.POST:
formset = layerForm(request.POST, queryset=layers_ordered)
pk_list = request.POST.get("layersOrder")
if formset.is_valid():
for form in formset:
instance = form.instance
instance.position = pk_list.index(instance.pk)
instance.save()
save_link = u"/ezmapping/map/%s" % (map_name)
return HttpResponseRedirect(save_link)
else:
formset = layerForm(queryset=layers_ordered)
return render_to_response("ezmapping/manage_map_Options.html", {'formset': formset}, context_instance=RequestContext(request))
形式:
class LayerMapOptionsForm(ModelForm):
link = forms.CharField(label='link', required=False)
def __init__(self, *args, **kwargs):
super(LayerMapOptionsForm, self).__init__(*args, **kwargs)
self.fields['link'].widget = ModelLinkWidget(self.instance.layer)
class Meta:
model = LayerMapOptions
fields = ['link', 'visible']
答案 0 :(得分:1)
您正在保存单个实例。相反,您需要在formset上调用save()来触发自动删除所选项。更仔细地阅读文档。
https://docs.djangoproject.com/en/1.5/topics/forms/formsets/#can-delete
如果您使用的是ModelFormSet,则在调用formset.save()时将删除已删除表单的模型实例。另一方面,如果您使用的是普通的FormSet,则可以在formset的save()方法中处理formset.deleted_forms,因为没有关于删除表单意味着什么的一般概念。