我尝试在Django3.0中从我的一个表单中写一个clean方法,这里当用户选择production_process时clean方法没有得到任何值,并且在我的模板页面中出现一个错误Production process: Select a valid choice. That choice is not one of the available choices.
这是我的forms.py
class ProductionCapacityForm(forms.ModelForm):
date = forms.DateField(required=True, widget=forms.DateInput(attrs=
{
'class':'datepicker'
}))
def __init__(self, *args, **kwargs):
self.client = kwargs.pop('client')
self.request = kwargs.pop('request')
try:
self.work_time = kwargs.pop('work_time')
except:
pass
super(ProductionCapacityForm, self).__init__(*args, **kwargs)
self.fields['production_process'].queryset = ProductionProcess.objects.filter(is_deleted=False).values_list("name", flat=True).distinct()
self.fields['date'].widget.attrs\
.update({
'placeholder': 'Select Date',
'class': 'input-class_name'
})
def clean(self):
production_process = self.cleaned_data.get('production_process')
number_of_people = self.cleaned_data.get('number_of_people')
datee = self.cleaned_data.get('date')
pk = self.instance.pk
if production_process:
try:
if production_process not in ProductionCapacity.objects.get(client=self.client, date=datee,production_process=production_process.id):
self.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.id).exists():
raise forms.ValidationError('Production Process is already exists')
self.cleaned_data['number_of_people'] = number_of_people
self.cleaned_data['date'] = datee
return super(ProductionCapacityForm, self).clean()
class Meta:
model = ProductionCapacity
widgets = {
"date": McamDateInput1,
}
fields = ['date', 'production_process', 'number_of_people']
这是我的models.py
class ProductionCapacity(models.Model):
client = models.ForeignKey(Client,on_delete=models.CASCADE)
date = models.DateField(blank=True, null=True)
production_process = models.ForeignKey(ProductionProcess,on_delete=models.CASCADE,blank=True,null=True)
number_of_people = models.IntegerField(blank=True, null=True)
给你
2条答案
按热度按时间5hcedyr01#
我怀疑是因为这句台词:
get_object_or_404
在检索要显示的对象时使用。在这种情况下,您只在代码中检索它。您不需要404 http响应,这几乎肯定不是有效的生产过程。只要得到对象,如果它不存在,就会得到
None
。vawmfj5a2#
我对
clean()
方法做了一个小修改,以解决您遇到的production_proces
字段未包含在表单的cleaned_data
字典中的问题。试试这个:
这里主要的变化是我现在调用
super().clean()
来获取表单的cleaned_data
字典,而不是直接返回它,然后我用number_of_people
和datee
的清理值更新这个字典,最后,我返回更新的cleaned_data
字典,这确保了所有清理的字段都包含在cleaned_data
字典中。包括production_process
。