我正在尝试提供一个数据表,该表使用某些Django模型中的数据与用户输入的数据相结合,以帮助进行一些计算并显示结果-这些计算将是临时性的,而不是基于单个Django模型。
我当时认为最好的方法是创建一个表单集(显示为html表),其中包含禁用的表单字段和initial
数据(用于模型数据),其他字段供用户输入我们没有数据的计算位,最后为计算结果包括一个额外的禁用表单字段,我将在提交表单时填充该字段。提交表单后,我还无法更新表单数据,因此感觉我使用了错误的方法。有谁有更好的建议?
更新:我在文档中找到了这个,所以现在我想知道是否应该基于旧的表单集以某种方式创建新的表单集。
如果您有一个绑定的Form实例并想以某种方式更改数据,或者想将一个未绑定的Form实例绑定到某些数据,请创建另一个Form实例。无法更改Form实例中的数据。创建Form实例后,无论其是否有数据,您都应考虑其数据不可变。
到目前为止,我已经成功地通过将initial=[]
传递给表单集构造函数,一些用户输入字段(预期的权重和变化百分比)和结果字段来创建了一个包含一些禁用字段的表单集。 (我还对css进行了调整,以使禁用的字段没有边框,因此它们看起来不可编辑。)
def calc_view(request):
types = list(Type.objects.filter(user=...).values('type_id'))
CalcFormset = formset_factory(form=CalcForm, extra=0)
formset = CalcFormset(request.GET or None, initial=types, form_kwargs={'user': request.user})
if formset.is_valid():
for form in formset.forms:
form.set_result()
return render(request, 'calc.html', {'formset': formset})
CalcForm
类似于
class CalcForm(forms.Form):
type = ModelChoiceField(disabled=True, queryset=Type.objects.none())
weight = IntegerField(required=False, widget=TextInput())
change_pct = IntegerField(required=True, min_value=0, max_value=100, initial=100, widget=TextInput())
result = IntegerField(disabled=True, required=False)
def __init__(self, user, *args, **kwargs):
super(CalcForm, self).__init__(*args, **kwargs)
self.fields['type'].queryset = Type.objects.filter(user=user)
def set_result(self):
cleaned_data = super(CalcForm, self).clean()
# None of these update the value in the form shown to the user
# To try and set data just set some fixed values - should be a calculation based on the type, weight and change_pct
self.initial['result'] = 80
self.cleaned_data['result'] = 77
self.fields['result'].value = 66
很抱歉上面的代码中有错别字-我已经拿走了我现有的代码,并尽可能地删除/简化了我的要求