[Answered ]-Django form not getting value for clean method

1👍

I suspect it’s because of the line:

self.cleaned_data['production_process'] = get_object_or_404(ProductionProcess,client=self.client,id=production_process.id)

get_object_or_404 is used when you’re retrieving an object to display. In this case you’re retrieving it in code only. You don’t want a 404 http response, which almost certainly is not a valid production process.

Just get the object, and you’ll get None if it doesn’t exist.

0👍

I made a small modification to the clean() method to fix the issue you are experiencing with the production_proces field not being included in the form’s cleaned_data dictionary.

Try this:

def clean(self):
    cleaned_data = super().clean()
    production_process = cleaned_data.get('production_process')
    number_of_people = cleaned_data.get('number_of_people')
    datee = cleaned_data.get('date')
    pk = self.instance.pk
    if production_process:
        try:
            if production_process.id not in ProductionCapacity.objects.filter(client=self.client, date=datee, production_process=production_process).values_list('production_process__id', flat=True):
                cleaned_data['production_process'] = get_object_or_404(ProductionProcess, client=self.client, id=production_process.id)
        except:
            if ProductionCapacity.objects.filter(client=self.client, date=datee, production_process=production_process).exists():
                raise forms.ValidationError('Production Process is already exists')

    cleaned_data['number_of_people'] = number_of_people
    cleaned_data['date'] = datee

    return cleaned_data

The main change here is that I’m now calling super().clean() to get the form’s cleaned_data dictionary, instead of returning it directly. Then I’m updating this dictionary with the cleaned values for number_of_people and datee. Finally, I’m returning the updated cleaned_data dictionary. This ensures that all cleaned fields are included in the cleaned_data dictionary, including production_process.

Leave a comment