Django-两次执行for循环-一次不保存,一次不保存?

时间:2019-03-23 15:37:14

标签: django python-3.x csv

现在,我正在尝试使用所有即将保存在数据库中的信息来确认CSV上传。所以基本上像这样:“以下条目将要更新/创建。您要继续吗?”。

使用当前代码,我可以让用户知道哪些条目已更新/创建或重复。但这是在将其保存在数据库中之后发生的。我希望用户检查他所做的更改是否正确,然后才将其保存到数据库中。

这是我的views.py(只有相关的部分)

            csv_file = request.FILES['file']
            csv_file.seek(0)
            decoded_file = csv_file.read().decode('utf-8').splitlines()
            row_count = len(decoded_file)
            #print("d_file: ", decoded_file)
            reader = csv.reader(decoded_file)
            liste = list()
            s = False
            for row in reader:
                count += 1
                try:
                    datet = datetime.now().date()
                    datum = datet.strftime("%d.%m.%Y")
                    row[7] = datum
                    row[8] = str(request.user)
                    #d = [row[0], row[1], row[2], row[3], row[4]]
                    dataset1 = CSV5.objects.filter(gebaeudebereich=row[0],
                                                     gebaeudenummer=row[1], ebene=row[2],
                                                     raum=row[3], dose=row[4])#.values_list("gebaeudebereich", "gebaeudenummer",
                                                     #                                       "ebene", "raum", "dose")
                    dataset2 = CSV5.objects.filter(switch_ip=row[5], switch_port=row[6]).values_list("switch_ip", "switch_port")
                    ds1 = CSV5.objects.values_list("gebaeudebereich", "gebaeudenummer", "ebene",
                                                                      "raum", "dose")
                    ds2 = CSV5.objects.values_list("switch_ip", "switch_port")
                    #print("ds1: ", ds1)
                    print("dataset1: ", dataset1)
                    print("dataset2: ", dataset2)
                    print("dataset1: ", dataset1.exists())
                    print("dataset2: ", dataset2.exists())

                    if (dataset1.exists() and not dataset2.exists()):
                        #instance = get_object_or_404(CSV5, id=count)
                        print("Fall 1")
                        ins = CSV5.objects.filter(gebaeudebereich=row[0],
                                                     gebaeudenummer=row[1], ebene=row[2],
                                                     raum=row[3], dose=row[4])
                        #liste.append(ins.values_list())
                        #print("liste: ", liste)
                        print ("instance: ", ins)
                        # This is the part that is important, it should only run after I submit the ConfirmationForm so I have to do something like this, but somehow different
                        if s == True:
                            ins.update(switch_ip=row[5], switch_port=row[6])
                        updated_obj += 1
                    elif not dataset1.exists() and dataset2.exists():
                        print("Fall 2")
                        ins = CSV5.objects.filter(switch_ip=row[5], switch_port=row[6])
                        print("instance: ", ins)
                        #ins.update(switch_ip=None, switch_port=None)
                        if s == True:
                            ins.update(gebaeudebereich = row[0], gebaeudenummer = row[1], ebene = row[2], raum = row[3],
                                       dose = row[4])
                        print("dat2: ", dataset2)
                        updated_obj += 1
                    elif (dataset1.exists() and dataset2.exists()):
                        print("Fall 3")
                        #liste.append(dataset1)
                        #print("liste: ", liste)
                        duplicate_obj += 1
                    elif not (dataset1.exists() and dataset2.exists()):
                        print("Fall 4")
                        if s == True:
                            CSV5.objects.get_or_create(id=CSV5.objects.count() + 1, gebaeudebereich=row[0],
                                                         gebaeudenummer=row[1], ebene=row[2],
                                                         raum=row[3], dose=row[4], switch_ip=row[5], switch_port=row[6],
                                                         datum=row[7], akteur=row[8])
                        created_obj += 1
                except IndexError:
                    print("IndexError")
                    break
                except IntegrityError:
                    duplicate_obj += 1
                    print("IntegrityError")

            messages.success(request, "objects created: %s " % created_obj)
            messages.success(request, "objects updated: %s " % updated_obj)
            messages.success(request, "duplicate objects: %s " % duplicate_obj)


            messages.success(request, "Objects about to be created: %s " % created_obj)
            messages.success(request, "Objects about to be updated: %s " % updated_obj)
            messages.success(request, "Duplicates: %s " % duplicate_obj)
            #print("f", csv_file)
            form = ConfirmationForm(request.POST, request.FILES)
            return render(request, "appp/confirmation.html", {'form' : form})


    form = UploadFileForm()
    return render(
        request, "appp/file_upload.html", {"form": form}
    )

UploadFileForm是带有FileField的普通表单,ConfirmationForm只是用于提交数据的表单。因此,基本上,该过程将是:提交UploadFileForm,csv.reader读取CSV文件,然后将数据发送到服务器(但由于if s == True而无法保存,因此未保存在数据库中)。然后在我的ConfirmationForm中,当我提交时,应该再次执行循环,但是这次将保存到数据库。我真的希望我的问题很清楚。如果没有让我知道。任何帮助将不胜感激。

0 个答案:

没有答案