2015-04-02 11 views
6

Zorluk django.Durationfield Django yeni <a href="https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.DurationField">DurationField</a> modelleri için olan sorun biraz yaşıyorum Django 1.8</p> <p>yeni DurationField kullanılarak

Kullanıcıların web günlüğümdeki bir etkinliğin süresi 1 gün, 3 gün veya 5 gün olup olmadığını, varsayılan seçimin 3 gün olup olmadığını seçebilmelerini istiyorum. Ben DurationField beyan, Ardından aşağıdaki

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'),) 

: maketimin başında

, ben seçimler ilan maket için bir ModelForm yarattı

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

ve bunu render uygun şablon Formda, "3 gün" açılır menüde önceden seçilmiştir ve "1 gün" ve "5 gün" de seçenekler arasındadır. Ancak formu gönderdiğimde form onaylama hatası alıyorum "Geçerli bir seçim yap. 3 gün, 0:00:00 uygun seçeneklerden biri değil."

Ancak, varsayılan DurationField gelen seçimler kaldırıp ayrılırken:

duration = models.DurationField(default = MEDIUM) 

Ben herhangi bir sorun olmadan gönderebilirsiniz. Burada neyi yanlış yapıyorum?

cevap

0

Bazı modellerde timedeltatimedelta dizesi, render veya template biçimine dönüştürülmez.

Ve ModelDurationFieldField DurationField Çalışmıyor ...

Ben ChoiceField

kodu kullanarak bunu çözdü:

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'] 

Ben tavsiye veya olmasın değil bilmiyorum. .. Ben de neden django varsayılan olarak çalışmıyorum araştırıyorum ...

1

Sorun bu hata düzeltme bilet açıklanmıştır aynı problem oldu mu

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

düzeltmek django ekibi beklerken Bunu düzeltmek için

iyi yolu bu özel alanı kullanmaktır :

""" 
    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}, 
      ) 
+0

görünüyor Bu bilet gibi 1.8.3 https://docs.djangoproject.com/en/1.8/releases/1.8.3/ adresinde ele alındı. – nnyby

İlgili konular