テキストファイルを保存するためのフィールドを持つAutoPartというモデルを参照するDjangoフォームがあります。
次に、このフォームを使用して、1つのテキストファイルだけでなく、テキストファイルのアーカイブをアップロードしようとしています。私のスクリプトはアーカイブを解凍してから、各テキストファイルをデータベースに追加します。
私の問題は、アーカイブ全体で、すべてではなく1つのテキストファイルのみが保存されていることです。何かを上書きしているからなのかしら?
これが私のコードです:
の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()
の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