本文介绍了Django-ModelForm can_delete = True不适用于M2M(直通)模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
选中删除复选框后,提交表单时不会删除LayerMapOptions实例。否则,该表格对于所有其他字段都可以正常使用。
When the delete checkbox is checked, the LayerMapOptions instance is not deleted when the form is submitted. Otherwise the form is working perfectly for all other fields. Is there something special to do in the form for through model?
model:
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()
view:
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']
推荐答案
您正在保存单个实例。相反,您需要在表单集上调用save()来触发自动删除所选项目。仔细阅读文档。
You are saving single instances. Instead you need to call save() on the formset to trigger automatic removal of selected items. Read docs more carefully.
这篇关于Django-ModelForm can_delete = True不适用于M2M(直通)模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!