I have a Django form that references a model called AutoPart which has a field for storing a text file.
I’m then trying to use this form to upload an archive of text files, rather than just one text file. My script unzips the archive, and then adds each text file to the database.
My problem is that only ONE text file in the whole archive is being saved, rather than all of them. I’m wondering if this is because I’m overwriting something?
Here’s my code:
In views.py
def mass_upload(request):
tmpdir = tempfile.mkdtemp()
if request.method == "POST":
formtoadd = massform(request.POST, request.FILES)
if formtoaddpart.is_valid():
zipped = zipfile.ZipFile(request.FILES['content'], 'r')
zipped = zipped.extractall(tmpdir)
for (dirpath, dirnames, filenames) in os.walk(tmpdir):
if "__MACOSX" in dirnames:
dirnames.remove("__MACOSX")
for filename in filenames:
new_model = formtoaddpart.save(commit=False)
file = open(dirpath + "/" + filename, 'rb')
filecontent = file.read()
file.seek(0)
new_model.modelname = os.path.splitext(filename)[0]#.replace(" ", "")
modelname = new_model.modelname
manufacturer = new_model.manufacturer
new_model.adder = request.user
filetype = new_model.type
format = new_model.format
adder_id = new_model.adder.id
new_model.content=store_in_s3(filename, filecontent, filetype, modelname, format, manufacturer, adder_id)
new_model.save()
In forms.py
class massform(ModelForm):
def __init__(self, *args, **kwargs):
super(massform, self).__init__(*args,**kwargs)
self.is_update=False
choices = UniPart.objects.all().values('manufacturer').distinct()
modelname = forms.CharField (label="AutoPart", max_length=80, required= False)
manufacturer = forms.CharField (label="Manufacturer", max_length=80, required= False)
type = forms.TypedChoiceField (label="Type", choices = (("type1", "type1"), ("type2", "type2")), widget = forms.RadioSelect, required= True)
format = forms.TypedChoiceField (label="Format", choices = (("format1", "format1"), ("format2", "format2")),widget = forms.RadioSelect, required= True)
content = forms.FileField()
def __init__(self, *args, **kwargs):
super(massform, self).__init__(*args, **kwargs)
self.is_update = False
# self.fields['mychoicefield'].choices = \
# list(self.fields['mychoicefield'].choices) + [('new stuff', 'new')]
def clean(self):
if self.cleaned_data and 'modelname' not in self.cleaned_data:
raise forms.ValidationError("Some error message")
if not self.is_update:
return self.cleaned_data
return self.cleaned_data
if not self.is_update:
return self.cleaned_data
class Meta:
model = AutoPart
I’m pretty sure the line:
doesn’t return a new python instance of the model class.
Your best bet would be to output the newmodel.pk in the loop and see if it changes.
From experience, I know that if you want to edit an existing instance and save it as a new one, you can just do
newmodel.pk = Noneand Django will create a new instance.