我正在尝试上传csv文件,然后解析为xml格式但在保存之前"导入csv文件并将其保存为xml文件" 我有上传功能正常工作并正确保存;但是,我的问题是如何将上传的文件传递给解析为xml格式的函数。 我正在使用django python
Model.py
from django.db import models
from django.urls import reverse
from .validators import validate_file_extension
# Create your models here.
class DataFile(models.Model):
title = models.CharField(max_length=250)
description = models.CharField(max_length=1000)
file = models.FileField()
def __str__(self):
return self.title + ' - ' + self.description + ' - ' + self.file
这是我的form.py
from django import forms
from .models import DataFile
class FileForm(forms.ModelForm):
class Meta:
model = DataFile
fields = ['title', 'description', 'file' ]
这是我的view.py
def importing(request):
form = FileForm(request.POST or None)
if request.method == 'POST':
form = FileForm(request.POST, request.FILES)
if form.is_valid():
#here is where the passing supose to be
form = csv2xml(request.FILES['file'])
form.save()
return HttpResponseRedirect('http://127.0.0.1:8000')
return render(request, 'import.html', { 'form': form })
更新 我希望将上传的文件传递给:
的函数def csv2xml(csv_file):
xml = dicttoxml.dicttoxml(csv_file)
return xml
我希望将文件传递给csv2xml函数,进行转换,然后将其另存为xml
当我使用上述方法将其传递给函数时,它说:
AttributeError at /importing
'InMemoryUploadedFile' object has no attribute 'save'
答案 0 :(得分:0)
试试这个答案
def importing(request):
form = FileForm(request.POST or None)
if request.method == 'POST':
form = FileForm(request.POST, request.FILES)
if form.is_valid():
# here is where the passing supose to be
# Changes >>>>>>>>>
form = csv2xml(request.FILES['file'].read())
with open('myfile.xml', 'wb') as xml_file:
xml_file.write(form)
# form.save() No need
# Changes <<<<<<<<<<<<
return HttpResponseRedirect('http://127.0.0.1:8000')
return render(request, 'import.html', {'form': form})
答案 1 :(得分:-1)
执行此操作的最佳方法是在save
类的models.Model
方法中进行一些更改。在models.py
:
class DataFile(models.Model):
title = models.CharField(max_length=250)
description = models.CharField(max_length=1000)
file = models.FileField()
def save(self, *args, **kwargs):
if self.file:
""" Do Whatever you wanna do with the upload file here """
super(DataFile, self).save(*args, **kwargs)
这将对上传的文件进行必要的更改,然后再保存在服务器上。