[英]django - int argument must be a string or a number, not 'Tuple'
[英]Django form: Argument must be a string or a number, not 'method'
当尝试向我的表单中添加验证self.cleaned_data['field']
和cleaned_data = super(MyForm, self).clean()
,似乎都返回了“方法”变量。
在尝试以下验证时,我遇到TypeError: float() argument must be a string or a number, not 'method'
。
没有自定义验证,也会出现类似的错误。
forms.py:
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = ['row_control', 'date', 'hours']
def clean(self):
clean_data = super(EntryForm, self).clean()
hours = clean_data.get("hours")
if float(hours) <= 0.00:
raise forms.ValidationError("Hours worked must be more than 0.")
# Always return cleaned data
return clean_data
如果float(hours)<= 0.00:行是,则DEBUG页显示本地变量:
__class__ <class 'timesheet.forms.EntryForm'>
hours <bound method Field.clean of <django.forms.fields.DecimalField object at 0x1066ca668>>
self <EntryForm bound=True, valid=True, fields=(row_control;date;hours)>
clean_data {'date': <bound method Field.clean of <django.forms.fields.DateField object at 0x106649fd0>>,'hours': <bound method Field.clean of <django.forms.fields.DecimalField object at 0x1066ca668>>,'row_control': <bound method Field.clean of <django.forms.models.ModelChoiceField object at 0x106804668>>}
这是它正在使用的上下文。
views.py:
@login_required
def monthview(request, year, month):
# Initialise forms
row_control_form = RowControlForm(initial={'month_control_record': month_control_record})
entry_form = EntryForm()
# Making form fields hidden
entry_form.fields['row_control'].widget = forms.HiddenInput()
entry_form.fields['date'].widget = forms.HiddenInput()
row_control_form.fields['month_control_record'].widget = forms.HiddenInput()
# If user has submitted a form
if request.method == 'POST':
# If user submits row_control form
if 'row_control_submit' in request.POST:
instance_pk = request.POST["instance"]
try:
row_control_form = RowControlForm(request.POST, instance=RowControl.objects.get(pk=instance_pk))
except ValueError:
row_control_form = RowControlForm(request.POST)
if row_control_form.is_valid():
row_control_form.save()
elif 'entry_submit' in request.POST:
instance_pk = request.POST["instance"]
try:
entry_form = EntryForm(request.POST, instance=Entry.objects.get(pk=instance_pk))
except ValueError:
entry_form = EntryForm(request.POST)
if entry_form.is_valid():
entry_form.save()
return redirect('/' + year + '/' + month + '/')
if request.is_ajax():
rawrow = request.GET['row']
rawday = request.GET['day']
# Get the employee model for the user signed in
employee = Employee.objects.get(user=request.user)
# Get the first day of the month from URL
first_day_of_month = datetime.date(int(year), int(month), 1)
# Get the month_control_record for the user logged in and for the month
month_control_record = MonthControlRecord.objects.get(employee=employee, first_day_of_month=first_day_of_month)
the_row_control = RowControl.objects.filter(month_control_record=month_control_record);
if int(rawday) > 0:
the_row_control = the_row_control[int(rawrow)]
date = str(year) + '-' + str(month) + '-' + str(rawday)
try:
the_entry = Entry.objects.get(row_control=the_row_control, date=date)
instance = the_entry.pk
hours = str(the_entry.hours)
except Entry.DoesNotExist:
instance = None
hours = None
the_row_control = the_row_control.pk
data = {
'form': "entry",
'row_control': the_row_control,
'date': date,
'hours': hours,
'instance': instance,
}
data = json.dumps(data)
else:
instance = the_row_control[int(rawrow)]
departments = Department.objects.all()
departmentno = index_number_of_object(departments, instance.department) + 1
activites = Activity.objects.all()
activityno = index_number_of_object(activites, instance.activity) + 1
notes = instance.notes
data = {
'form': "row_control",
'department': departmentno,
'activity': activityno,
'instance': instance.pk,
'notes': notes,
}
print(data)
data = json.dumps(data)
return HttpResponse(data)
context = {
'row_control_form': row_control_form,
'entry_form': entry_form,
'year': year,
'month': month,
}
return render(request, "timesheet/monthview.html", context)
template.html:
<div class="" id="entry-form-container">
<form action="{{ request.path }}" class="form-inline" method=
"post">
{% csrf_token %}
{{ entry_form|crispy }}
<input id="entry_instance" name="instance" type="hidden">
<button class="btn btn-primary" name="entry_submit" type="submit" value="Submit">
<i class="fa fa-floppy-o"></i> Save
</button>
</form>
</div>
编辑:删除自定义验证,并且窗体完全无法验证,从标题中删除验证。
不太确定我出了什么问题/哪里出了问题,但这可以解决:
forms.py:
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = ['row_control', 'date', 'hours']
def clean(self):
cleaned_data = self.cleaned_data
if cleaned_data['hours'] <= 0:
raise forms.ValidationError("Hours worked must be more than 0.")
# Always return cleaned data
return cleaned_data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.