删除Django表单中带有复选框的项

2024-10-04 11:22:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在和Django一起写表格。表单是某个模型的模型表单,Experiment。每个Experiment都有多个关联的TimeSlot模型,用ForeignKey('Experiment')定义。我想要一个表单,它可以通过复选框从EditExperimentForm中删除一个或多个TimeSlot实例。在

目前,我通过EditExperimentForm中init函数中的一个循环来定义模型中的所有复选框:

def __init__(self, *args, **kwargs):
    super(EditExperimentForm,self).__init__(*args,**kwargs)
    experiment = self.instance
    for timeslot in experiment.timeslot_set.all():
        self.fields['timeslot-'+str(timeslot.id)] = BooleanField(label="Remove Timeslot at "+str(timeslot.start),required=False)

然后我用正则表达式处理它们:

^{pr2}$

这远不是一个优雅的解决方案(首先,它使得除了最通用的模板之外的任何东西都成为一个直接的噩梦。有人能想出一个更简单的方法吗?在


Tags: django模型self表单定义initargskwargs
2条回答

这段代码没有经过测试,但类似这样的代码应该可以做到:

class MyForm(forms.Form):
    # You can change the queryset in the __init__ method, but this should be a nice basis
    timeslots = forms.ModelMultipleChoiceFieldqueryset=Timeslot.objects.all(), widget=forms.CheckboxSelectMultiple)

    def save(self):
        # make sure you do a form.is_valid() before trying to save()
        for timeslot in self.cleaned_data['timeslots']:
            timeslot.delete()

如果您为时隙对象使用模型窗体集,这可能是一个更干净的解决方案。你看了吗?在

http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1

相关问题 更多 >