Login

NonTimeSplitDateTimeField

Author:
jturnbull
Posted:
April 2, 2009
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

Variation on SplitDateTimeField that does not enforce the Time to be required, accepting a default instead.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class NonTimeSplitDateTimeField(forms.SplitDateTimeField):
    
    """Variation on SplitDateTimeField that does not enforce the Time to be
    required, accepting a default instead.
    
    example usage:
    
    class MonkeyForm(forms.ModelForm):

        start_date = NonTimeSplitDateTimeField(
            default_time=datetime.time(00,00,00),
            widget=widgets.AdminSplitDateTime(), required=False )
        end_date = NonTimeSplitDateTimeField(
            default_time=datetime.time(11,59,59),
            widget=widgets.AdminSplitDateTime(), required=False )
    
    """
    
    
    def __init__(self, default_time, *args, **kwargs):
        self.default_time = default_time
        return super(NonTimeSplitDateTimeField, self).__init__(
            *args, **kwargs)
        
        
    def compress(self, data_list):
        if data_list:
            # Raise a validation error if date is empty
            # (possible if SplitDateTimeField has required=False).
            if data_list[0] in EMPTY_VALUES:
                raise ValidationError(self.error_messages['invalid_date'])
            if data_list[1] in EMPTY_VALUES:
                # Rather than raising an error (as super does) use the
                # default time passed in the constructor
                data_list[1] = self.default_time
            return datetime.datetime.combine(*data_list)
        return None

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.