Snowman08 Snowman08 - 2 months ago 21x
Python Question

Custom formset validation not working in django

In my formset I would like to check each reading against a target if the reading is larger than the target do not save to db. For some reason I can't get this to work correctly because it still allows me to save. Any help would be greatly appreciated!

all in

#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):
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")

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 =
for n_i in new_instance:

n_i.created_at =
n_i.updated_at =
form_errors = formset.errors

return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
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,
'dim_description': dims.description,
'work_order': sheet_data.work_order,
'customer_name': sheet_data.customer_name,
'serial_sample_number': serial_sample_number,


<h1>Inspeciton Values</h1>
<div class="well">
<form method="post">
{% csrf_token %}
{{ formset.management_form }}
{% for x in formset.forms %}
Sample Number {{ forloop.counter0|add:serial_sample_number }}
{{ x }}
{{ x.errors }}
{% endfor %}
<input type="submit" value="Submit Values" class="btn-primary" />


The Django docs on custom formset validation show that you should create a clean method.

You have named your method insp_clean, so Django will never call it. Rename the method to clean.