2011-01-19 9 views

risposta

9

C'è un frammento here, che imposta il giorno per 1 (presumendo che hai un DateField che questo valore finirà in, avrete bisogno di ottenere una sorta di giorno).

il codice è come questo (nel caso in cui frammenti di Django scompare):

import datetime 
import re 

from django.forms.widgets import Widget, Select 
from django.utils.dates import MONTHS 
from django.utils.safestring import mark_safe 

__all__ = ('MonthYearWidget',) 

RE_DATE = re.compile(r'(\d{4})-(\d\d?)-(\d\d?)$') 

class MonthYearWidget(Widget): 
    """ 
    A Widget that splits date input into two <select> boxes for month and year, 
    with 'day' defaulting to the first of the month. 

    Based on SelectDateWidget, in 

    django/trunk/django/forms/extras/widgets.py 


    """ 
    none_value = (0, '---') 
    month_field = '%s_month' 
    year_field = '%s_year' 

    def __init__(self, attrs=None, years=None, required=True): 
     # years is an optional list/tuple of years to use in the "year" select box. 
     self.attrs = attrs or {} 
     self.required = required 
     if years: 
      self.years = years 
     else: 
      this_year = datetime.date.today().year 
      self.years = range(this_year, this_year+10) 

    def render(self, name, value, attrs=None): 
     try: 
      year_val, month_val = value.year, value.month 
     except AttributeError: 
      year_val = month_val = None 
      if isinstance(value, basestring): 
       match = RE_DATE.match(value) 
       if match: 
        year_val, month_val, day_val = [int(v) for v in match.groups()] 

     output = [] 

     if 'id' in self.attrs: 
      id_ = self.attrs['id'] 
     else: 
      id_ = 'id_%s' % name 

     month_choices = MONTHS.items() 
     if not (self.required and value): 
      month_choices.append(self.none_value) 
     month_choices.sort() 
     local_attrs = self.build_attrs(id=self.month_field % id_) 
     s = Select(choices=month_choices) 
     select_html = s.render(self.month_field % name, month_val, local_attrs) 
     output.append(select_html) 

     year_choices = [(i, i) for i in self.years] 
     if not (self.required and value): 
      year_choices.insert(0, self.none_value) 
     local_attrs['id'] = self.year_field % id_ 
     s = Select(choices=year_choices) 
     select_html = s.render(self.year_field % name, year_val, local_attrs) 
     output.append(select_html) 

     return mark_safe(u'\n'.join(output)) 

    def id_for_label(self, id_): 
     return '%s_month' % id_ 
    id_for_label = classmethod(id_for_label) 

    def value_from_datadict(self, data, files, name): 
     y = data.get(self.year_field % name) 
     m = data.get(self.month_field % name) 
     if y == m == "0": 
      return None 
     if y and m: 
      return '%s-%s-%s' % (y, m, 1) 
     return data.get(name, None) 
+0

sei un uomo saggio! Grazie. – ApPeL

+0

ad ogni modo è possibile avere gli elementi visualizzati in ordine DESC e NON ASC, quindi se dovessi passare gli anni dal 1970 al 2011, per il 2011 da mostrare per primi. – ApPeL

+0

@ApPeL - sicuro - Immagino di aggiungere 'self.years.reverse()' alla fine di '__init__' farebbe il trucco (scusami per aver impiegato così tanto tempo a rispondere, sono stato fuori SO per alcuni giorni). –

0

mi sono imbattuto lo stesso problema di oggi e risolto rimuovendo il campo giorno tramite una proprietà CSS e impostando 1 come valore per la giornata di pulizia.

#id_my_date_field_day-button { 
    display: none; 
} 

ho usato un ModelForm con UpdateView e quindi aveva dati iniziali nei miei campi, che reso la vita un po 'più semplice perché ho sempre avuto un valore valido per il giorno di my_date_field.

Problemi correlati