【问题标题】:Can't get model to be saved getting error: "TypeError expected string or bytes-like object"无法保存模型,出现错误:“TypeError 预期字符串或类似字节的对象”
【发布时间】:2018-06-26 19:06:06
【问题描述】:

我正在尝试从几个模型中获取信息并在模型日历中生成表条目。我无法保存日历条目。得到一个类型错误。最终,我希望这个系统根据最后一个预定的星期一将日历条目添加到未来。但目前这项任务只会在星期一执行。但如果可能的话,我希望能够提前一周以上。

模板:

<form action="{% url 'portal:custom_admin' %}" method="post">
    {% csrf_token %}
    <div style="background-color:red; width:15%;">
        <button name="submit">Project</button>
        DANGER! Only click on mondays, until future projecter can go based off futuremost monday generated into Calendar
    </div>
</form>

我正在苦苦挣扎的视图:

def custom_admin(request):
"""
Displays MaxSettings, also
Takes time_slots and create a week of it into the future (only should be done on mondays)
Note:eventually this should be able to generate from the last monday in the calendar instead of today
"""
max_settings = MaxSettings.objects.filter()
time_slots = TimeSlots.objects.filter()

if request.method != 'POST':
    pass
    # Do nothing
else:
    # Project A week forward
    for slot in time_slots:
         #there will be an if statement for each weekday
        if slot.day.weekday == 'Monday':
            new_entry = Calendar(
                date=datetime.timedelta(days=7),
                timeslot_A=slot.timeslot_A,
                timeslot_B=slot.timeslot_B,
                booked=False
            )
            new_entry.save()
            return HttpResponseRedirect(reverse('portal:custom_admin'))

calendar = Calendar.objects.filter()

context = {
    'max_settings': max_settings,
    'calendar': calendar,
}
return render(request, 'portal/custom_admin.html', context)

以下是相关模型:

class MaxSettings(models.Model):
"""
Everyweek day has its own specified open/close time, time slots along with number of available jobs
"""
MONDAY = 'Monday'
TUESDAY = 'Tuesday'
WEDNESDAY = 'Wednesday'
THURSDAY = 'Thursday'
FRIDAY = 'Friday'
SATURDAY = 'Saturday'
SUNDAY = 'Sunday'
WEEKDAY_CHOICES = (
    (MONDAY, 'monday'),
    (TUESDAY, 'tuesday'),
    (WEDNESDAY, 'wednesday'),
    (THURSDAY, 'thursday'),
    (FRIDAY, 'friday'),
    (SATURDAY, 'saturday'),
    (SUNDAY, 'sunday'),
)
weekday = models.CharField(max_length=9, choices=WEEKDAY_CHOICES, )
operating = models.BooleanField()
start_work_time = models.TimeField()
end_work_time = models.TimeField()

def __str__(self):
    """Return a string representation of the model."""
    return self.weekday


class TimeSlots(models.Model):
"""time slots along with number of available jobs for that slot"""
day = models.ForeignKey(MaxSettings, on_delete=models.CASCADE)
timeslot_A = models.TimeField()
timeslot_B = models.TimeField()
max_jobs = models.PositiveSmallIntegerField()

def __str__(self):
    """Return a string representation of the model."""
    return '%s %s %s' % (self.timeslot_A, self.timeslot_B, self.day)


class Calendar(models.Model):
"""
this will get it details from TimeSlots and be generated into the future from the  MaxSettings
"""
date = models.DateField()
timeslot_A = models.TimeField()
timeslot_B = models.TimeField()
booked = models.BooleanField()

错误详情:

TypeError at /custom_admin/

expected string or bytes-like object

Request Method:     POST
Request URL:    http://127.0.0.1:8000/custom_admin/
 Django Version:    2.0
Exception Type:     TypeError
Exception Value: expected string or bytes-like object

Exception Location:         error location: /site-packages/django/utils/dateparse.py in parse_date, line 74

【问题讨论】:

  • 你让我们猜测错误发生在哪里。请编辑问题以包含完整的错误回溯消息。
  • @JohnGordon 我说“我正在努力的观点”并且在那个观点中只有一个 .save()... 错误位置:/site-packages/django/utils/dateparse。 py 在 parse_date,第 74 行
  • @JohnGordon 要求将信息添加到问题中
  • 所以new_entry = Calendar(...)成功了,但是new_entry.save()有错误?
  • @JohnGordon 是的,如果我删除 new_entry.save() 行并提交表单,我不会收到任何错误。

标签: python django python-3.x django-models django-views


【解决方案1】:

我的猜测是发生错误是因为您使用 datetime.timedelta 作为 Calendar 的 date 属性的值> 进入。 Django 需要的是 datetime.date。 更准确地说,Django 需要一个日期(例如:“2018-01-17”),而您只提供两个日期之间的差异(在您的情况下:“7 天”)。您的代码应该做的是计算下周一的日期,然后将该值(转换为 datetime.date)传递给 Calendar.date 属性。

【讨论】:

  • 谢谢,这就是问题所在。你想解释一下我怎样才能避免只在星期一这样做并且只预测未来一周吗?而是说计划到未来 12 周?
  • 我会在这里坦率地说:不,我不能。在您的原始帖子中,您没有描述您如何构建应用程序、您期望的输入或您计划如何计算日历的日期。没有任何上下文,任何人都能做的最好的事情就是猜测。不要误会我的意思,我愿意提供帮助,但我需要更多信息才能使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-29
  • 1970-01-01
  • 2019-10-31
  • 1970-01-01
  • 2020-11-09
  • 2017-03-14
相关资源
最近更新 更多