I have a model as follows:
AGE_GROUPS = (
('<1', '<1'),
('1-4', '1-4'),
('5-9', '5-9'),
('10-14', '10-14'),
('15-19', '15-19'),
('20-24', '20-24'),
('25-29', '25-29'),
('30-34', '30-34'),
('35-39', '35-39'),
('40-44', '40-44'),
('45-49', '45-49'),
('50+', '50+'),
)
class Data(models.Model):
dataset = models.ForeignKey('data.Dataset', on_delete=models.CASCADE)
indicator = models.ForeignKey('data.Indicator', on_delete=models.CASCADE)
facility = models.CharField(max_length=120, choices=FACILITIES)
month = models.CharField(max_length=20)
age_group = models.CharField(max_length=10, choices=AGE_GROUPS)
male = models.PositiveIntegerField(blank=True, null=True)
female = models.PositiveIntegerField(blank=True, null=True)
And a form and formset as follows:
class DataForm(forms.ModelForm):
class Meta:
model = Data
fields = ['age_group', 'male', 'female']
DataFormset = forms.modelformset_factory(Data, form=DataForm, extra=len(AGE_GROUPS))
And this is the problem:
In the template, I want the formset to be rendered as a table for all the age groups with the Age groups prefilled. Better still, is there a way to have the Age Group as a non-editable column, but the male and female editable? Mind you if the particular record already has values (for male and female), then the respective formset row should be prefilled as well.
Here's my view so far:
def home(request):
data_formset = DataFormset(request.POST or None)
# -> The below code is not working when the model has existing data
# (I'm open to any approach)
# Prefill the Age Groups in the formset
# for i, form in enumerate(data_formset):
# if form.fields['age_group'] == None:
# form.fields['age_group'].initial = AGE_GROUPS[i][0]
# Handle POST Request
if request.method == 'POST':
if data_formset.is_valid():
for record in data_formset.cleaned_data:
data = Data.objects.create(
# ... other logic to handle the other fields in the model
**record
)