View django days-of-week in a model

I have this "Jobs Server" model that I am creating. I want to include a field in which the days of the week that this work will work will be saved. Ultimately, in the user interface, I would like the user to have a series of flags (one for each day) that they can select. What would be the best way to present the "days of the 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 = ? 
+7
source share
4 answers

If you need a checkbox for each of them, then the easiest way to create BooleanFields for each of them. If you want to save it as a more complex value (for example, a comma-separated list or something else), create your own widget and play with javascript, then you can go along this route.

+2
source

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

This code leads to automatic translation into the local language using multilingual tools.

 #myFields.py from django.utils.translation import ugettext as _ from django.db.models import SmallIntegerField 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() (..) 
+20
source

Something like this will 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 save a few days

 #models.py class Days(models.Model): day = models.CharField(max_length=8) days = models.ManyToManyField(Days) #forms.py widgets = { 'days': forms.CheckboxSelectMultiple } 
+11
source

Just implemented by django-weekday-field . Works great! Hope this helps other people who stumble over this question.

+1
source

All Articles