CSV文件import-Django(仅导入1行数据)

时间:2020-09-30 13:17:59

标签: python django django-views export-to-csv

我正在尝试将CS​​V文件内容上传到数据库,但是观察到只有第一行数据正在更新,而且如果存在具有相同值的数据,那么它将被忽略。 我们还可以将open与逻辑配合使用,以便一旦任务完成,它应该自动关闭。 我的Views.py

import csv, io
from django.shortcuts import render
from django.contrib import messages
# Create your views here.
# one parameter named request
def contact_upload(request):
    # declaring template
    template = "testapp/upload.html"
    data = Movie.objects.all()
# prompt is a context variable that can have different values      depending on their context
    prompt = {
        'order': 'Order of the CSV should be releasedate, moviename, hero, heroine, rating',
        'profiles': data
              }

    # GET request returns the value of the data with the specified key.
    if request.method == "GET":
        return render(request, template, prompt)

    csv_file = request.FILES['file']
    # let's check if it is a csv file
    if not csv_file.name.endswith('.csv'):
        messages.error(request, 'THIS IS NOT A CSV FILE')
    data_set = csv_file.read().decode('UTF-8')
    print(data_set)
    io_string = io.StringIO(data_set)
    next(io_string)
        # setup a stream which is when we loop through each line we are able to handle a data in a stream

    for column in csv.reader(io_string, delimiter=',', quotechar="|"):
        _, created = Movie.objects.update_or_create(
            releasedate=column[0],
            moviename=column[1],
            hero=column[2],
            heroine=column[3],
            rating=column[4]
        )
        context = {}
        return render(request, template, context)

models.py 从django.db导入模型中

在这里创建模型。

class Movie(models.Model):
   releasedate=models.DateField()
   moviename=models.CharField(max_length=30)
   hero=models.CharField(max_length=30)
   heroine=models.CharField(max_length=30)
   rating=models.IntegerField(unique=True)

   def __str__(self):
      return self.moviename

有几次我得到异常值:
'utf-8'编解码器无法解码位置15的字节0xe4:无效的连续字节如何使用try块进行处理。

[30/Sep/2020 12:59:36] "GET /admin/jsi18n/ HTTP/1.1" 200 3223
releasedate,moviename,hero,heroine,rating
2020-09-30,bndcxnv,Abcd,fdghfkd,67
2020-09-76,Abcd,abc,abc,1
2020-09-10,Xyz,Pp,Ff,77
2020-09-30,Huff,Fgf,Fgt,779
[30/Sep/2020 12:59:47] "POST /uploadcsv HTTP/1.1" 200 470
[30/Sep/2020 12:59:50] "GET /admin/testapp/movie/ HTTP/1.1" 200 7245
[30/Sep/2020 12:59:50] "GET /admin/jsi18n/ HTTP/1.1" 200 3223

0 个答案:

没有答案