我正在尝试为Django管理员后端创建表单字段 在数据库中,它应该是CharField字段,包含长度为24 * 7的“0”和“1”值。 在管理面板中,我希望将它们视为7个字段,每个字段有24个复选框。 代码:
model.py:
from django.db import models
from places.widgets import *
from places.fields import *
class Place(models.Model):
…
time = HoursWorkByWeekField()
…
fields.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)
widgets.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)
当我尝试syncdb时,我有错误:
TypeError: Error when calling the metaclass bases unhashable type: 'dict'