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.
CodePudding user response:
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')]
CodePudding user response:
I would write a Form, i.e. 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.