2 years ago
#351424
amiller
How to instantiate model with init function in modelforms?
I have a program that uploads a csv of data in order to map values in the csv to other values. In order to do this, the user must select which columns in the csv they need to create the mapping, so that no extraneous information is on the mapping page.
To do this I created a dynamic Django by overriding the init function in my ModelForm. The problem is that even though I'm able to dynamically show the column values, when the user tries to select the values and save them to the model, it fails, because the Model choices don't align with the dynamic checkbox values. So I've overridden the Model's init function to populate the model's choices. My problem is I'm not sure how to instantiate the model in the ModelForm to call the init function.
model
class ColumnMapping(models.Model):
CHOICES =[('row_1', 'A'), ('row_2', 'B'), ('row_3', 'C')]
company = models.ForeignKey(RawData, on_delete=models.CASCADE)
columnNames = MultiSelectField(max_length=100, choices=CHOICES)
def __init__(self, *args, **kwargs):
self.choices = kwargs.pop('choices')
super(ColumnMapping, self).__init__(*args, **kwargs)
self._meta.get_field.choices = self.choices
form - I think something needs to happen here in the Meta class, but since the model = ColumnMapping
line doesn't instantiate the model (I don't think), I don't think I can pass variables to it.
class ColumnMappingForm(ModelForm):
def __init__(self, *args, **kwargs):
self.choices = kwargs.pop('choices')
super(ColumnMappingForm, self).__init__(*args, **kwargs)
self.fields['columnNames'].widget.attrs.update({'class': 'form-check'})
self.fields['columnNames'].choices = self.choices
class Meta:
model = ColumnMapping
fields = ('columnNames',)
views
def columnSelection(request, companyName):
companyData = RawData.objects.get(companyName = companyName)
columnNames = list(RawData.objects.get_columnNames(companyData.file.name))
columnNamesTuple = ()
for columnName in columnNames:
tup = (columnName, columnName)
columnNamesTuple = list(columnNamesTuple)
columnNamesTuple.append(tup)
columnNamesTuple = tuple(columnNamesTuple)
if request.method == "POST":
form = ColumnMappingForm(request.POST, choices=columnNamesTuple)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse("mappingApp:productMapping", kwargs={'companyName': companyData.companyName}))
else:
error = list(form.errors.values())[0]
return render(request, "mappingApp/columnSelection.html", {
"form": form,
"columnNames": columnNames,
"company": companyData,
"error": error
})
else:
form = ColumnMappingForm(choices=columnNamesTuple)
return render(request, "mappingApp/columnSelection.html", {
"form": form,
"columnNames": columnNames,
"company": companyData
})
python
django
django-models
modelform
0 Answers
Your Answer