Commits

Matthew Schinckel committed f075f68 Merge

Merge changes from Andrew Gall

Comments (0)

Files changed (5)

     class MyModel(models.Model):
         weekdays = weekday_field.fields.WeekdayField()
 
+
+There is also a BitwiseWeekdayFormField, contributed by Andrew Gall <housepage@gmail.com>, which stores the data in a single integer.
 
 setup(
     name = "django-weekday-field",
-    version = "0.1",
+    version = "1.0",
     description = "Weekday field for django models",
     url = "http://bitbucket.org/schinckel/django-weekday-field/",
     author = "Matthew Schinckel",

weekday_field/fields.py

 
     def get_db_prep_value(self, value, connection=None, prepared=False):
         return ",".join([str(x) for x in value])
-    
+
 try:
     from south.modelsinspector import add_introspection_rules
     add_introspection_rules([], ['^weekday_field\.fields\.WeekdayField'])

weekday_field/forms.py

 from django import forms
 
 import utils
+import operator
 
 class WeekdayFormField(forms.TypedMultipleChoiceField):
     def __init__(self, *args, **kwargs):
-        kwargs['choices'] = utils.DAY_CHOICES
+        if 'choices' not in kwargs:
+          kwargs['choices'] = utils.DAY_CHOICES
         kwargs.pop('max_length', None)
-        kwargs['widget'] = forms.widgets.SelectMultiple
+        if 'widget' not in kwargs:
+          kwargs['widget'] = forms.widgets.SelectMultiple
         super(WeekdayFormField, self).__init__(*args, **kwargs)
         
     def clean(self, value):
-        value = super(WeekdayFormField, self).clean(value)
-        return ",".join([str(x) for x in value])
+      value = super(WeekdayFormField, self).clean(value)
+      return value
+
+class BitwiseWeekdayFormField(WeekdayFormField):
+  def __init__(self, *args, **kwargs):
+    if 'short' in kwargs:
+      if kwargs['short']:
+        kwargs['choices'] = [(x[0],x[1]) for x in utils.BITWISE_DAY_CHOICES]
+      del kwargs['short']
+    else:
+      kwargs['choices'] = [(x[0],x[2]) for x in utils.BITWISE_DAY_CHOICES]
+    super(BitwiseWeekdayFormField, self).__init__(*args, **kwargs)
+
+  def clean(self,value):
+    value = [int(x) for x in value]
+    if len(value) != 0:
+      value = reduce(operator.or_, value)
+    else:
+      value = 0
+    return value

weekday_field/utils.py

     (6, "Sunday")
 )
 
+BITWISE_DAY_CHOICES = (
+    (1, "Su","Sunday"),
+    (2, "M","Monday"),
+    (4, "Tu","Tuesday"),
+    (8, "W","Wednesday"),
+    (16, "Th","Thursday"),
+    (32, "F","Friday"),
+    (64, "Sa","Saturday"),
+)