I want to upload a CSV file in the admin that adds information to a model. In case you can live with a normal form and not a extension of change_form.html
and not overwriting response_change
(I tried that fist) this is how it can be done:
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
class StoreAdminForm(forms.ModelForm):
## add an extra field:
upfile = forms.FileField()
class Meta:
model = Store
fields = "__all__"
def clean(self):
cleaned_data = super(StoreAdminForm, self).clean()
if "upfile" in self.changed_data:
### file validation on file type etc here ..
## file is valid:
## next lines deal with the InMemoryUploadedFile Type
path = settings.MEDIA_ROOT.joinpath("___tmp___")
tmp = default_storage.save(path, ContentFile(cleaned_data["upfile"].read()))
## open file
with open(tmp_file, encoding = "utf8") as f:
data = f.readlines()
## ...
I hope this helps everyone, I lost some time with not knowing how to deal with the InMemoryUploadedFile
types.