Django-使用Forms的嵌套循环和模板渲染

时间:2019-03-26 10:29:01

标签: django python-3.x forms templates render

是否可以在return语句后设置变量?

我正在尝试使用if子句执行for循环。首先,如果if子句为False,则在完全执行for循环之后,它应使用表单呈现模板,然后将变量设置为True。然后再次执行for循环,但是这一次它应执行if语句并提交类似于(“确定吗?”然后单击“继续”或“取消”)的Form。我使用嵌套循环(while循环内的for循环)进行了尝试,但使用请求返回模板的return render语句之后无法再设置变量。

这是我的views.py

def file_upload(request):
    if request.method == "POST":
            # Wenn CSV Datei valide ist --> Datei hochladen
            csv_file = request.FILES['file']
            csv_file.seek(0)
            decoded_file = csv_file.read().decode('utf-8').splitlines()
            reader = csv.reader(decoded_file)
            updated_list = list()
            created_list = list()
            s = False
            form2 = ConfirmationForm(request.POST, request.FILES)
            while (True):
                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("count: ", count)
                        print("dataset1: ", dataset1)
                        print("dataset2: ", dataset2)
                        print("dataset1: ", dataset1.exists())
                        print("dataset2: ", dataset2.exists())
                        print("s: ", s)

                        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)
                            if form2.is_valid() and s == True:
                                ins.update(switch_ip=row[5], switch_port=row[6], datum = row[7], akteur = row[8])
                            else:
                                updated_list.append(ins)
                            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)
                            if form2.is_valid() and s == True:
                                ins.update(gebaeudebereich = row[0], gebaeudenummer = row[1], ebene = row[2], raum = row[3],
                                           dose = row[4], datum = row[7], akteur = row[8])
                            else:
                                updated_list.append(ins.values_list())
                                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 form2.is_valid() and s == True:
                                ins = 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_list.append(ins)
                                ins.save()
                            created_obj += 1
                    except IndexError:
                        print("IndexError")
                        break
                    except IntegrityError:
                        duplicate_obj += 1
                        print("IntegrityError")


                if s != False:
                    messages.success(request, "objects created: %s " % created_obj)
                    messages.success(request, "objects updated: %s " % updated_obj)
                    messages.success(request, "duplicate objects: %s " % duplicate_obj)
                    break

                elif s == False:
                    messages.success(request, "Einträge die neu hinzugefügt werden: %s " % created_list)
                    messages.success(request, "Einträge die überschrieben werden: %s " % updated_list)
                    messages.success(request, "Duplikate: %s " % duplicate_obj)

                    form = ConfirmationForm()
                    return render(request, "appp/confirmation.html", {'form' : form})

                s = True

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

这是我的确认表:

class ConfirmationForm(forms.Form):
    class Meta:
        model = CSV5
        fields = ('gebaeudebereich', 'gebaeudenummer', 'ebene', 'raum', 'dose',
                  'switch_ip', 'switch_port', 'datum', 'akteur',)

confirmation.html

{% extends 'appp/base.html' %}
{% block body %}

<h2>Bestätigung</h2>

{% if user.is_authenticated %}

    {% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" onclick="return confirm('Sollen die angezeigten Daten in der Datenbank gespeicher werden?')">Speichern</button>
</form>


<a href = "{% url 'appp:index' %}">
<button>Cancel</button>
</a>

{% endif %}
{% endblock %}

最后是我的models.py

class CSV5(models.Model):
    gebaeudebereich = models.CharField(max_length=100, blank=True, null=True)
    gebaeudenummer = models.CharField(max_length=100, blank=True, null=True)
    ebene = models.CharField(max_length=100, blank=True, null=True)
    raum = models.CharField(max_length=100, blank=True, null=True)
    dose = models.CharField(max_length=100, blank=True, null=True)
    switch_ip = models.CharField(max_length=100, blank=True, null=True)
    switch_port = models.CharField(max_length=100, blank=True, null=True)
    datum = models.CharField(max_length=100)
    akteur = models.CharField(max_length=100)

    class Meta:
        unique_together = (("gebaeudebereich", "gebaeudenummer", "ebene", "raum", "dose"), ("switch_ip", "switch_port"))

因此,由于s为False,因此for循环遍历每个条目。它无需实际查询数据库即可进行验证。在for循环执行后,我使用ConfirmationForm在其中将要更改的数据显示给用户,然后将s设置为True。但是,由于我使用return语句,因此无法将变量设置为True。 任何帮助将不胜感激。

0 个答案:

没有答案