Django DateField TypeError 预期的字符串或类似字节的对象
Posted
技术标签:
【中文标题】Django DateField TypeError 预期的字符串或类似字节的对象【英文标题】:Django DateField TypeError expected string or bytes-like object 【发布时间】:2019-05-15 08:43:44 【问题描述】:我是 Django 新手, 提交并尝试保存在下拉列表之一中选择的更新值时出现错误。 我认为这与传递给表单的日期有关,但我不确定如何解决此问题。
回溯错误:
match = date_re.match(value)
TypeError:预期的字符串或类似字节的对象
我的模型.py
> from django.db import models
class Person(models.Model):
person_name = models.CharField(max_length=50, unique=True)
person_dept = models.ForeignKey('Department',
default='1',
on_delete=models.CASCADE)
number = models.CharField(max_length=10, unique=True)
email = models.EmailField(max_length = 100, unique=True)
class Meta():
db_table = 'person'
def save(self, *args, **kwargs):
for field_name in ['person_name']:
val = getattr(self, field_name, False)
if (val):
setattr(self, field_name, val.title())
super(Person, self).save(*args, **kwargs)
def __str__ (self):
return self.person_name
class Department(models.Model):
dept_desc = models.CharField(max_length=100, unique=True)
class Meta():
db_table = 'dept'
def __str__ (self):
return self.dept_desc
class Roster(models.Model):
roster_date = models.DateField()
oss_person = models.ForeignKey('Person',
on_delete=models.CASCADE,
related_name='+',
limit_choices_to='person_dept': 1,)
nw_person = models.ForeignKey('Person',
on_delete=models.CASCADE,
related_name='+',
limit_choices_to='person_dept': 2,)
class Meta():
db_table = 'roster'
def __str__(self):
return str(self.roster_date)
我的表单.py
> from datetime import datetime, timedelta
from django import forms
from django.core import validators
from roster.models import Roster, Person, Department
class UpdateRosterForm(forms.ModelForm):
class Meta():
model = Roster
fields = '__all__'
labels =
"roster_date":"Start On Call Date",
"oss_person":"Servers",
"nw_person":"Networks",
def __init__(self, *args, **kwargs):
super(UpdateRosterForm, self).__init__(*args, **kwargs)
self.today = datetime.now()
self.min_date = (self.today - timedelta(days=self.today.weekday())
+ timedelta(days=0)).date()
self.fields['roster_date'] = forms.ModelChoiceField(
queryset=Roster.objects.filter(
roster_date__gte=self.min_date),
initial = 0,
label='Start On Call Date')
def clean(self):
roster_date = self.cleaned_data.get("roster_date")
oss_person = self.cleaned_data.get("oss_person")
nw_person = self.cleaned_data.get("nw_person")
我的模板文件
% extends "roster/base.html" %
% block title %Update On Call Roster% endblock %
% block extra_js %
% load staticfiles %
<script type="text/javascript" src='% static "js/roster_selector.js" %'></script>
% endblock extra_js %
% block body_block %
<p>
<div class="container">
<form name="status_form" method="POST">
% include 'roster/messages.html' %
% block content %
% endblock %
</form>
</div>
<div class="container">
<table class="table table-bordered table-striped table-dark table-primary">
<colgroup span="3"></colgroup>
<thead>
<th scope="col">On Call Start Date</th>
<th scope="col">Server</th>
<th scope="col">Networks</th>
</thead>
<trbody>
<form method="POST">
<tr>
% for field in form %
<td> field </td>
% endfor %
</tr>
% csrf_token %
</trbody>
</table>
<input class="btn btn-primary" type="submit" value="submit">
</div>
% endblock %
我的意见.py
>def update(request):
form = forms.UpdateRosterForm()
if (request.method == 'POST'):
form = forms.UpdateRosterForm(request.POST)
if (form.is_valid()):
form.save()
form = forms.UpdateRosterForm()
messages.success(request,"Roster Has Been Updated Successfully")
else:
messages.warning(request,"Something Went Wrong!")
return render(request, 'roster/update.html', 'form': form)
def send_selected_date(request):
if (request.method == "GET"):
sel_date = request.GET.get('selected_date')
oncall_ids = Roster.objects.filter(
roster_date = sel_date).values_list('oss_person_id','nw_person_id')
oncall_ids_json = dumps(list(oncall_ids), cls=DjangoJSONEncoder)
return HttpResponse(oncall_ids_json)
追溯
追溯: 内部文件“/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/core/handlers/exception.py” 34. 响应 = get_response(请求) _get_response 中的文件“/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/core/handlers/base.py” 126. 响应 = self.process_exception_by_middleware(e,请求) _get_response 中的文件“/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/core/handlers/base.py” 124.响应=wrapped_callback(请求,*callback_args,**callback_kwargs) 文件 更新中的“/Users/msl/Documents/scripts/django/oncall_roster/roster/views.py” 115. if (form.is_valid()): is_valid 中的文件“/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/forms/forms.py” 185. 返回 self.is_bound 而不是 self.errors 错误中的文件“/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/forms/forms.py” 180. self.full_clean() full_clean 中的文件“/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/forms/forms.py” 383. self._post_clean() 文件“/Users/msl/Documents/scripts/django/env/lib/python3.6/site- _post_clean 中的 packages/django/forms/models.py" 403. self.instance.full_clean(排除=排除, 验证唯一=假) full_clean 中的文件“/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/db/models/base.py” 1130. self.clean_fields(排除=排除) clean_fields 中的文件“/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/db/models/base.py” 1172. setattr (self, f.attname, f.clean(raw_value, self)) 清理文件“/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/db/models/fields/__init__.py” 630. 值 = self.to_python(值) to_python 中的文件“/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/db/models/fields/__init__.py” 1230.解析=解析日期(值) parse_date 中的文件“/Users/msl/Documents/scripts/django/env/lib/python3.6/site-packages/django/utils/dateparse.py” 74. 匹配 = date_re.match(值) 异常类型:/update_roster/ 处的 TypeError 异常值:预期的字符串或类似字节的对象【问题讨论】:
【参考方案1】:在您的模型中,您有 bakeer_date 一个 DateField,但您从 Form 发送了一个 Roaster 对象,这就是您面临此问题的原因。所以像这样更新表格:
days = self.today - self.min_date
choices = list()
choices.append((self.today, str(self.today)))
new_date = self.today
for i in range(days):
new_date = new_date - datetime.timedelta(days=1)
choices.append((new_date, str(new_date)))
self.fields['roster_date'].widget = forms.Select(choices=choices)
【讨论】:
感谢您的回复。如果我从 ModelChoiceField() 更改为 DateField() ,则它不再是下拉列表。我想将其保留为下拉菜单,以便用户可以选择日期。以上是关于Django DateField TypeError 预期的字符串或类似字节的对象的主要内容,如果未能解决你的问题,请参考以下文章
Django 中 DateField 的 RuntimeWarning
我的 django 模型 DateField 如何将 30 天添加到提供的值?