我有一个非常简单的django表单,用于租用默认为用户截止日期的密钥,用户可以更改日期,然后继续保存表单。但是每当我保存key_instance
时,django都会抛出error: expected string or bytes-like object
。我知道datetime对象导致此错误,因为如果我评论它一切正常。这是我的views.py和forms.py
forms.py:
class UpdateKeyRequestForm(forms.Form):
APPROVE_CHOICES = [
('d', 'Deny this key request'),
('a', 'Approve this key request')
]
request_status = forms.CharField(label='Please select to accept or deny this request.',widget=forms.Select(choices=APPROVE_CHOICES))
due_date = forms.DateField(help_text='Enter a date (YYYY-MM-DD) between now and 4 weeks (default 3). ')
def clean_due_date(self):
due_date = self.cleaned_data['due_date']
approved_status = self.cleaned_data['request_status']
# Check date is not in past.
if due_date < datetime.date.today():
raise ValidationError(_('Invalid date - renewal in past'))
if due_date > datetime.date.today() + datetime.timedelta(weeks=4):
raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead'))
return due_date, approved_status
views.py:
@permission_required('catalog.can_mark_returned')
def update_key_request(request, pk):
"""
View function for renewing a specific keyInstance by admin
"""
key_inst=get_object_or_404(KeyInstance, pk=pk)
# If this is a POST request then process the Form data
if request.method == 'POST':
# Create a form instance and populate it with data from the request (binding):
form = UpdateKeyRequestForm(request.POST)
# Check if the form is valid:
if form.is_valid():
# process the data in form.cleaned_data as required (here we just write it to the model due_back field)
request_status = form.cleaned_data['request_status']
due_date = form.cleaned_data['due_date']
if request_status == 'a':
key_inst.due_back = due_date
key_inst.status = 'o'
key_inst.date_out = datetime.date.today()
key_inst.save()
else:
key_inst.status = 'a'
key_inst.save()
# redirect to a new URL:
return HttpResponseRedirect(reverse('all-available-keys'))
else:
default_due_date = datetime.date.today() + datetime.timedelta(weeks=3)
form = UpdateKeyRequestForm(initial={'due_date': default_due_date})
#If this is a GET (or any other method) create the default form.
return render(request, 'catalog/roomkey_request_update.html', {'form': form, 'keyinst': key_inst})
但问题是我用完全相同的方法实现了这个确切的逻辑来更新截止日期并且它仍然正常工作。我很困惑为什么这个会抛出错误。任何人都可以请一些亮点?
这是错误页面上的本地var:
due_date
(datetime.date(2018, 6, 13),)
form
<UpdateKeyRequestForm bound=True, valid=True, fields=(due_date)>
key_inst
<KeyInstance: Conestogo River (3fc9458a-5ec8-46a3-a04e-6a48e650b15f)>
pk
UUID('3fc9458a-5ec8-46a3-a04e-6a48e650b15f')
request
<WSGIRequest: POST '/catalog/key/3fc9458a-5ec8-46a3-a04e-6a48e650b15f/update'>
答案 0 :(得分:3)
您的clean_due_date
方法只应返回due_date
。
def clean_due_date(self):
...
return due_date
您似乎没有在该方法中使用approved_status
,因此我会从方法中删除此行
approved_status = self.cleaned_data['request_status']
如果您确实需要clean fields that rely on each other,那么您应该使用clean()
方法而不是clean_<fieldname>
方法执行此操作。