Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django days-of-week representation in model

I have this "Jobs Server" model that i'm building. I want to include a field that will save which days of the week this job will run on. Ultimately in the UI, i would like the user to be able to have a series of check boxes(one for each day) that they can select. What would be the best way to represent this "days-of-week" data in my mode?

class Job(models.Model):
    name = models.CharField(max_length=32, unique=True)
    package = models.ForeignKey(Package)
    binary = models.ForeignKey(Binary)
    host = models.ForeignKey(Host)
    colo = models.ForeignKey(Location)
    group = models.ForeignKey(Group)
    type = models.ForeignKey(Type)
    start = models.TimeField()
    end = models.TimeField()
    days = ?
like image 797
nnachefski Avatar asked May 11 '11 15:05

nnachefski


3 Answers

You may want to create DayOfTheWeek field type, which you can improve in various ways.

This code cause to translate automatically into the local language using the multilingual tools.

#myFields.py
from django.utils.translation import ugettext as _

DAY_OF_THE_WEEK = {
    '1' : _(u'Monday'),
    '2' : _(u'Tuesday'),
    '3' : _(u'Wednesday'),
    '4' : _(u'Thursday'),
    '5' : _(u'Friday'),
    '6' : _(u'Saturday'), 
    '7' : _(u'Sunday'),
}

class DayOfTheWeekField(models.CharField):
    def __init__(self, *args, **kwargs):
        kwargs['choices']=tuple(sorted(DAY_OF_THE_WEEK.items()))
        kwargs['max_length']=1 
        super(DayOfTheWeekField,self).__init__(*args, **kwargs)

#models.py
import myFields
(..)
    dayOfTheWeek = myFields.DayOfTheWeekField()
(..)
like image 53
MUY Belgium Avatar answered Nov 16 '22 12:11

MUY Belgium


Something like this would work.

#models.py
DAYS_OF_WEEK = (
    (0, 'Monday'),
    (1, 'Tuesday'),
    (2, 'Wednesday'),
    (3, 'Thursday'),
    (4, 'Friday'),
    (5, 'Saturday'),
    (6, 'Sunday'),
)

days = models.CharField(max_length=1, choices=DAYS_OF_WEEK

#forms.py
widgets = { 'days': forms.CheckboxSelectMultiple }

Or to save multiple days

#models.py
class Days(models.Model):
    day = models.CharField(max_length=8)

days = models.ManyToManyField(Days)

#forms.py
widgets = { 'days': forms.CheckboxSelectMultiple }
like image 23
silent1mezzo Avatar answered Nov 16 '22 12:11

silent1mezzo


If you want a checkbox for each one, then the easiest thing to do is to create BooleanFields for each of them. If you want to store it as a more complex value (eg. comma separated list or something), create your own widget and play with javascript, then you could go that route.

like image 3
Bryce Siedschlaw Avatar answered Nov 16 '22 11:11

Bryce Siedschlaw