我正在尝试为 Django 管理后端创建表单字段在数据库中它应该是 CharField 字段,包含长度为 24*7 的“0”和“1”值。在管理面板中,我希望将它们视为 7 个字段,每个字段有 24 个复选框。编码:
模型.py:
from django.db import models
from places.widgets import *
from places.fields import *
class Place(models.Model):
…
time = HoursWorkByWeekField()
…
字段.py
from django.forms import fields
from django.db import models
from places.widgets import HoursWorkByWeekWidget
class HoursWorkByWeekField(models.CharField):
widget = HoursWorkByWeekWidget
def __init__(self):
super(HoursWorkByWeekField, self).__init__(max_length=24*7, min_length=24*7)
def to_python(self, value):
return list(value)
def get_db_prep_value(self, value):
result = []
for i in range(24*7):
if value[i] :
result += ['1']
else :
result += ['0']
return ''.join(result)
小部件.py
from django.forms import widgets
class HoursWorkByDayWidget(widgets.CheckboxSelectMultiple):
def render(self, name, attrs=None):
choices = range(0,24,1)
return widgets.CheckboxSelectMultiple.render(self, name, attrs, choices)
class HoursWorkByWeekWidget(widgets.MultiWidget):
def __init__(self, attrs=None):
widgets = (
HoursWorkByDayWidget(),
HoursWorkByDayWidget(),
HoursWorkByDayWidget(),
HoursWorkByDayWidget(),
HoursWorkByDayWidget(),
HoursWorkByDayWidget(),
HoursWorkByDayWidget(),
)
super(HoursWorkByWeekWidget, self).__init__(widgets, attrs)
当我尝试同步数据库时出现错误:
TypeError: Error when calling the metaclass bases unhashable type: 'dict'