Reputation: 145
I am trying to create an integer field connected with a drop down box to collect a time period from a user. From there i would like to store it in a table in some sort of readable format for the machine e.g 12W from that i can split the object and add 12 weeks on to todays date and fill a Due Date field.
For example
[12][Days]
[weeks]
[Months]
Would this be a customer widget? or is there a better way of completed it?
Upvotes: 0
Views: 2100
Reputation: 1057
INT_CHOICES = [(x, x) for x in range(1, 60)]
in the model:
date_interval = models.PositiveIntegerField(choices=INT_CHOICES, default=1)
in the model form:
class SomeForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['x1', 'x2'..., 'date_interval']
widgets = {'date_interval': forms.Select(choices=INT_CHOICES)
and that should do the trick.
I am a little surprised that the "forms.ChoiceField" in the answer above can works. See how to use forms choicefield inside modelform.
Upvotes: 1
Reputation: 2335
If you want just a form you could use 2 form fields, both of which are already present in Django, and their default widgets.
IntegerField (forms) + ChoiceField (forms) with choices something like [[0, "Days"],[1, "Weeks"],[2, "Months"],]
So it would look like:
class MyForm(forms.Form):
amount = forms.IntegerField(label='Your name')
units = forms.ChoiceField(choices=[[0, "Days"],[1, "Weeks"],[2, "Months"],])
If you want a model to store these 2 values separately, you could use (IntegerField (models) and some field of your preference with choices). Then use a ModelForm, so you will not need to define any fields on your form anymore.
In case you want even more machine-frieldly format than 2 separate values... Check whether your database can store intervals and consider using DurationField. However you will lose the possibility to automatically create neat form with 2 widgets.
Upvotes: 1