我在和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}$这远不是一个优雅的解决方案(首先,它使得除了最通用的模板之外的任何东西都成为一个直接的噩梦。有人能想出一个更简单的方法吗?在
这段代码没有经过测试,但类似这样的代码应该可以做到:
如果您为时隙对象使用模型窗体集,这可能是一个更干净的解决方案。你看了吗?在
http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1
相关问题 更多 >
编程相关推荐