views.py
@login_required()
def Info_anlegen(request, id=None):
item = get_object_or_404(Kunden, id=id)
kontaktform_form = InfoForm(request.POST or None, instance=item)
if WindowsHome.objects.filter(KN=item.KN).exists():
item1 = WindowsHome.objects.get(KN=item.KN)
winform_form = InfoWinForm(request.POST or None, instance=item1)
if kontaktform_form.is_valid():
return redirect('/Verwaltung/KontaktAnlegen')
else:
form = acroniform(instance=item)
return render(request, 'blog/infokontakt.html',
{'kontaktform_form': kontaktform_form, 'winform_form': winform_form})
infokontakt.html
{% extends 'blog/base.html' %}
{% load bootstrap4 %}
{% block supertitle %} InfoPage {% endblock %}
{% block Content %}
{% load static %}
<html>
<div class="p-2 mb-1 bg-white text-black">
<head>
<div class="d-flex justify-content-center align-items-center container ">
<img src="{% static 'blog/Gubler.jpeg' %}" alt="Gubler" height="300" width="700">
</div>
</head>
<br>
<body>
<form class="form-row" action="" method="post">
<div style="margin-left: 2.5em;">
<font color="black">
<div class="col-sm-10 col-form-label">
{% csrf_token %}
{% bootstrap_form kontaktform_form %}
</div>
</font>
</div>
</form>
<form class="form-row" action="" method="post">
<div style="margin-left: 2.5em;">
<font color="black">
<div class="col-sm-10 col-form-label">
{% csrf_token %}
{% bootstrap_form winform_form %}
</div>
</font>
</div>
</form>
我的问题是:
如果WindowsHome.KN存在,则会显示
但是如果不存在我会得到错误
UnboundLocalError at /Verwaltung/InfoKontakt/6
local variable 'winform_form' referenced before assignment
Request Method: GET
Request URL: http://127.0.0.1:8000/Verwaltung/InfoKontakt/6
Django Version: 3.0.1
Exception Type: UnboundLocalError
Exception Value:
local variable 'winform_form' referenced before assignment
我怎么说,如果数据库条目不存在,则不应显示该表单? 要么 如果数据库条目不存在,则显示一个空格“”
答案 0 :(得分:1)
您尝试将winform_form
发送到模板,但是如果WindowsHome.objects.filter(KN=item.KN).exists()
为假,则不会设置该模板。
您可能应该执行以下操作:
@login_required()
def Info_anlegen(request, id=None):
context = {}
item = get_object_or_404(Kunden, id=id)
kontaktform_form = InfoForm(request.POST or None, instance=item)
if WindowsHome.objects.filter(KN=item.KN).exists():
item1 = WindowsHome.objects.get(KN=item.KN)
winform_form = InfoWinForm(request.POST or None, instance=item1)
context['winform_form'] = winform_form
if kontaktform_form.is_valid():
return redirect('/Verwaltung/KontaktAnlegen')
else:
form = acroniform(instance=item)
context['kontaktform_form'] = kontaktform_form
return render(request, 'blog/infokontakt.html', context)
答案 1 :(得分:1)
您可以在方法开始时将 winform_form 初始化为“无”,这样它就不会引发该错误。 (即)
import requests
token='Bearer aslkdjndskgns'
endpoint = 'https://aap.xyz'
data = {'number':'9177903753951'}
headers={"authorization":token}
a=(requests.post(endpoint, data=data, headers=headers).json())
print(a)
,也可以在模板中使用django模板标签 {%if%} ... {%endif%}
即
def Info_anlegen(request, id=None):
winform_form = None # Do like this
item = get_object_or_404(Kunden, id=id)