0

我有一个 Django 表单,它引用了一个名为 AutoPart 的模型,该模型有一个用于存储文本文件的字段。

然后,我尝试使用此表单上传文本文件的存档,而不仅仅是一个文本文件。我的脚本解压缩存档,然后将每个文本文件添加到数据库中。

我的问题是整个档案中只有一个文本文件被保存,而不是全部。我想知道这是否是因为我正在覆盖某些东西?

这是我的代码:

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
4

1 回答 1

1

I'm pretty sure the line:

new_model = formtoaddpart.save(commit=False)

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 = None and Django will create a new instance.

于 2013-02-03T04:49:28.613 回答