Good afternoon. I have a task to store in the database a string, 24 * 7 long, consisting of zeros and ones. In the admin panel, I want to see seven columns with 24 checkboxes in each: if the checkbox is checked, then 1 is put in the corresponding place in the line in the database, if it is unchecked – 0.
To implement this I am trying to write my own field and widget
The following is a description of the model (partially) model.py:
from django.db import models from places.widgets import * from places.fields import * class Place(models.Model): … time = HoursWorkByWeekField() …
Further, in fact, 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)
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)
When you try to run syncdb after the time attribute is not created in the database.
Try to add
__metaclass__ = models.SubfieldBase