语境
我需要构建一个表单集以允许将开放时间设置为一周。
地位
这是我的开放时间模型:
WEEKDAYS = [
(1, _("Monday")),
(2, _("Tuesday")),
(3, _("Wednesday")),
(4, _("Thursday")),
(5, _("Friday")),
(6, _("Saturday")),
(7, _("Sunday")),
]
class OpeningHours(models.Model):
user = models.ForeignKey(User)
weekday = models.IntegerField(choices=WEEKDAYS)
from_hour = models.TimeField()
to_hour = models.TimeField()
class Meta:
unique_together = (('user', 'weekday'),)
这是我为默认周设置生成表单集的方式
UserOpeningHoursFormSet = formset_factory(UserOpeningHoursForm, extra=0)
hours = [{
'weekday': day,
'from_hour': '08:00',
'to_hour': '18:00',
} for day in range(1, 8)]
formset = UserOpeningHoursFormSet(initial=hours)
这是我如何获得当前用户的营业时间
user_hours = request.user.openinghours_set.all()
问题
如何将 user_hours 放入我的表单集中?
编辑
例如,假设用户已经在数据库中设置了星期一和星期四的时间,表单应该类似于:
weekday: Monday
from_hour: '09:00' # user_set
to_hour: '19:00' # user_set
weekday: Tuesday
from_hour: # default initial value
to_hour: # default initial value
weekday: Wednesday
from_hour: # default initial value
to_hour: # default initial value
weekday: Thursday
from_hour: '13:00' # user_set
to_hour: '15:00' # user_set
weekday: Friday
from_hour: # default initial value
to_hour: # default initial value
weekday: Saturday
from_hour: # default initial value
to_hour: # default initial value