Durationfield django

Difficulty using the new DurationField in Django 1.8

I am having problems with Django new DurationField for models.

I want the user to be able to choose whether the duration of the event on my web server is 1 day, 3 days, or 5 days, with a default of 3 days.

At the beginning of my model, I declare a choice:

SHORT = datetime.timedelta(days=1) MEDIUM = datetime.timedelta(days=3) LONG = datetime.timedelta(days=5) DURATION_CHOICES = ((SHORT, '1 day'),(MEDIUM, '3 days'), (LONG, '5 days'),) 

Then below I declare a DurationField:

 duration = models.DurationField(choices = DURATION_CHOICES, default = MEDIUM) 

I created a model model for the model and displayed it on the appropriate template. In the “3 days” form, the selected choice was in the drop-down list, as well as “1 day” and “5 days”. However, when I submit the form, I get a form validation error "Select the correct option. 3 days, 0:00:00 is not one of the available options."

However, when I remove the selection from the DurationField and leave it by default:

 duration = models.DurationField(default = MEDIUM) 

I can send without any problems. What am I doing wrong here?

+6
source share
2 answers

The same problem was explained in this big big bit

https://code.djangoproject.com/ticket/24897

The best way to fix this is to use this custom field while waiting for the django command to fix this:

  """ This is a temp DurationField with a bugfix """ standard_duration_re = re.compile( r'^' r'(?:(?P<days>-?\d+) (days, )?)?' r'((?:(?P<hours>\d+):)(?=\d+:\d+))?' r'(?:(?P<minutes>\d+):)?' r'(?P<seconds>\d+)' r'(?:\.(?P<microseconds>\d{1,6})\d{0,6})?' r'$' ) # Support the sections of ISO 8601 date representation that are accepted by # timedelta iso8601_duration_re = re.compile( r'^P' r'(?:(?P<days>\d+(.\d+)?)D)?' r'(?:T' r'(?:(?P<hours>\d+(.\d+)?)H)?' r'(?:(?P<minutes>\d+(.\d+)?)M)?' r'(?:(?P<seconds>\d+(.\d+)?)S)?' r')?' r'$' ) def parse_duration(value): """Parses a duration string and returns a datetime.timedelta. The preferred format for durations in Django is '%d %H:%M:%S.%f'. Also supports ISO 8601 representation. """ match = standard_duration_re.match(value) if not match: match = iso8601_duration_re.match(value) if match: kw = match.groupdict() if kw.get('microseconds'): kw['microseconds'] = kw['microseconds'].ljust(6, '0') kw = {k: float(v) for k, v in six.iteritems(kw) if v is not None} return datetime.timedelta(**kw) class DurationField(CoreDurationField): def to_python(self, value): if value is None: return value if isinstance(value, datetime.timedelta): return value try: parsed = parse_duration(value) except ValueError: pass else: if parsed is not None: return parsed raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, ) 
+1
source

Somehow, the choices model choices not choices line when render or convert to template .

And Model DurationField Field DurationField Doesn't Work ...

I solved it using ChoiceField

code:

 class TestForm(ModelForm): SHORT_1 = str(timedelta(days=1)).replace('day,', '') SHORT = SHORT_1.replace(' ',' ') MEDIUM_1 = str(timedelta(days=3)).replace('days,', '') MEDIUM = MEDIUM_1.replace(' ',' ') LONG_1 = str(timedelta(days=-5)).replace('days,', '') LONG = LONG_1.replace(' ',' ') DURATION_CHOICES = ((SHORT, '1 day'),(MEDIUM, '3 days'), (LONG, '5 days'),) duration = forms.ChoiceField(widget = forms.Select(), choices = (DURATION_CHOICES), initial='MEDIUM', required = True,) class Meta: model = Test fields = ['duration'] 

I do not know if this is not recommended or not ... I'm too looking for why django does not work by default ...

0
source

Source: https://habr.com/ru/post/984634/


All Articles