在我的formset中,如果读数大于目标不保存到db,我想检查针对目标的每个读数。出于某种原因,我不能让它正常工作,因为它仍然允许我保存。任何帮助将不胜感激!
全部在views.py
中 #custom formset validation
def get_dim_target(target):
dim = Dimension.objects.values_list('target', flat=True).filter(id=target)
return dim
#custom formset validation
class BaseInspecitonFormSet(BaseFormSet):
def insp_clean(self):
if any(self.errors):
return
reading = []
for form in self.forms:
dim_id = form.cleanded_data['dimension_id']
reading = form.cleaned_data['reading']
target = get_dim_target(dim_id)
if reading > target:
raise forms.ValidationError("Reading larger than target")
reading.append(reading)
#formset
def update_inspection_vals(request, dim_id=None):
dims_data = Dimension.objects.filter(id=dim_id)
can_delete = False
dims = Dimension.objects.get(pk=dim_id)
sheet_data = Sheet.objects.get(pk=dims.sheet_id)
serial_sample_number = Inspection_vals.objects.filter(dimension_id=24).values_list('serial_number', flat=True)[0]
target = Dimension.objects.filter(id=24).values_list('target', flat=True)[0]
title_head = 'Inspect-%s' % dims.description
if dims.ref_dim_id == 1:
inspection_inline_formset = inlineformset_factory(Dimension, Inspection_vals, can_delete=False, extra=0, fields=('reading',), widgets={
'reading': forms.TextInput(attrs={'cols': 80, 'rows': 20})
})
if request.method == "POST":
formset = inspection_inline_formset(request.POST, request.FILES, instance=dims)
if formset.is_valid():
new_instance = formset.save(commit=False)
for n_i in new_instance:
n_i.created_at = datetime.datetime.now()
n_i.updated_at = datetime.datetime.now()
n_i.save()
else:
form_errors = formset.errors
formset.non_form_errors()
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
else:
formset = inspection_inline_formset(instance=dims, queryset=Inspection_vals.objects.filter(dimension_id=dim_id).order_by('serial_number'))
return render(request, 'app/inspection_vals.html',
{
'formset': formset,
'dim_data': dims_data,
'title':title_head,
'dim_description': dims.description,
'dim_target': dims.target,
'work_order': sheet_data.work_order,
'customer_name': sheet_data.customer_name,
'serial_sample_number': serial_sample_number,
})
inspection_val.html
<h1>Inspeciton Values</h1>
<div class="well">
<form method="post">
{% csrf_token %}
<table>
{{ formset.management_form }}
{% for x in formset.forms %}
<tr>
<td>
Sample Number {{ forloop.counter0|add:serial_sample_number }}
</td>
<td>
{{ x }}
{{ x.errors }}
</td>
</tr>
{% endfor %}
</table>
<input type="submit" value="Submit Values" class="btn-primary" />
</form>
</div>
</div>
答案 0 :(得分:1)
custom formset validation上的Django文档显示您应该创建clean
方法。
您已将方法命名为insp_clean
,因此Django永远不会调用它。将方法重命名为clean
。