简体   繁体   中英

how to convert a range of dates to fill in for a drop down list in django

class Trade(models.Model):
    user_id = models.CharField(max_length=5, null=True, blank=True)
    nse_index = models.ForeignKey('NseIndex', on_delete=models.CASCADE)
    trade_expiry = models.DateField(default=THURSDAYS[0], choices=THURSDAYS)
    trade_type = models.CharField(max_length=25, choices=TRADE_TYPE, default="paper")
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)

I need to display the trade_expiry(all thursdays in a year) as a tuple to be displayed as a dropdown list on a form using Django.

This can be done with a list comprehension, something like this is possible:

def all_specific_days(year, day):
  d = datetime.date(year, 1, 1)
  d += datetime.timedelta(days= d.weekday() - day)
  days = []
  while d.year == year:
      days.append(d)
      d += datetime.timedelta(days=7)
  return days

THURSDAYS = all_specific_days(2023, 3)
THURSDAYS_CHOICES = [(i, d) for i, d in enumerate(THURSDAYS)]

This will return a list which looks like the following:

[(0, datetime.date(2023, 1, 4)), (1, datetime.date(2023, 1, 11)),
...(51, datetime.date(2023, 12, 27))]

I hope this helps you out, with this you can even specify which year and which day you want. Remember Monday = 0 and Sunday = 6, so Thursday = 3.

EDIT:

THURSDAYS_CHOICES = [(i, str(d)) for i, d in enumerate(THURSDAYS)]

Will give back a list with the string representation of a date ->

[(0, '2023-01-04'), (1, '2023-01-11'), (2, '2023-01-18')... 
..., (51, '2023-12-27')]

I would write a Form, ie something like this:

class SelectOperatorChoiceForm(forms.Form):
    operator_select = forms.ModelChoiceField(queryset=None, label="choose the operator:")

def __init__(self, operators, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['operator_select'].queryset = operators  

in my case, when creating an instance of the form, operators is a queryset. I think you can adapt easily this code to your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM