将数据从csv文件存储到Django中的模型中?

时间:2019-05-16 10:51:01

标签: python django csv

我正在使用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中存储文件

1 个答案:

答案 0 :(得分:0)

我最终按照docs中的描述在Django中使用了FileSystemStorage类。