我正在使用POST
方法从表单提交csv文件,并希望将其内容保存到模型中
forms.py
class SaveCsvForm(forms.Form):
upload_file = forms.FileField(label="Uplaod CSV File", help_text="Uploa file in CSV format")
Views.py
def save_csv(request):
if request.method == 'POST':
form = SaveCsvForm(request.POST, request.FILES)
if form.is_valid():
print("All ok I am check One")
# instance = CsvStorage(file_field=request.FILES['file'])
file = request.FILES['upload_file'].read()
print(file)
csv_to_db(file)
ack = {
'status': 'Success',
'message': 'Data is successfuly submited into database'
}
return JsonResponse(ack)
else:
ack = {
'status': 'Error',
'message': 'Server Returned '+form.errors.as_json(),
}
return JsonResponse(ack)
else:
form = SaveCsvForm()
return render(request, 'upload_csv.html', {'form': form})
用于在模型中存储数据的文件处理程序方法
def csv_to_db(filename):
with open(filename, 'r') as file:
''' reading csv file in dictionary format '''
reader = csv.DictReader(file)
for row in reader:
instance = CsvStorage(username=row['username'],
first_name=row['user'],
city=row['city'],
mobile=row['mobile']
)
instance.save()
if instance:
return({'status': 'successfuly'})
else:
return({'status': 'error'})
注意:
1。主要问题是在读取文件时
2。我不想在模型fileField
中存储文件