questnofinterest
questnofinterest

Reputation: 329

Can't get model to be saved getting error: "TypeError expected string or bytes-like object"

I'm trying to take info from a few models and generate table entries in the model Calendar. I cannot get it to save the Calendar entry. Getting a TypeError. Eventually I would like this system to add calendar entries into the future based of the last scheduled monday. But currently this task will only be performed on mondays. But I would like to be able to project more than one week forward if possible.

Template:

<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>

View with which I am struggling:

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)

Here are the relevant models:

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()

Error Details:

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

Upvotes: 2

Views: 455

Answers (1)

domochevski
domochevski

Reputation: 553

My guess would be that the error happens because you're using a datetime.timedelta as a value for the date property of your Calendar entry. What Django needs is a datetime.date. To be more precise, Django needs a date (e.g.: "2018-01-17"), while you are only providing a difference between two dates (in your case: "7 days"). What your code should do is compute the date for the next Monday and then pass that value (cast as a datetime.date) to the Calendar.date property.

Upvotes: 3

Related Questions