[英]local variable referenced before assignment django error
This is my view.py and when i have a form which when i submit with the required fields it gives an appropriate output but when i don't input anything in the form and click submit i get an error saying "local variable 'researcher' referenced before assignment". 这是我的view.py,当我有一个表单,当我使用必填字段提交表单时,它会提供适当的输出,但是当我在表单中不输入任何内容并单击提交时,我会收到一条错误消息,提示“本地变量'researcher'分配前引用”。
Also i want to know how do i keep my form data saved on the destination page 我也想知道如何将表格数据保存在目标页面上
def about_experiment(request,ex_link_name):
if request.method == 'POST':
form = AboutHelp(request.POST)
if form.is_valid():
researcher = form.cleaned_data['researcher']
study = form.cleaned_data['study']
else:
form = AboutHelp()
return render(request, 'about_experiment.html', {'researcher': researcher, 'study': study})
my form on the source page is 我在源页面上的表单是
<form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST" name="form">
{% csrf_token %}
<label>Researcher Name(s):<input type="text" name="researcher">
<lable>Study Summary<textarea rows="10" cols="50" placeholder="here you go" maxlength="500" class="form-control" name="study"></textarea>
<br>
<input type = "submit" value="Submit" class="btn btn-primary" />
</form>
My destination page where the form outputs are present 表单输出所在的我的目标页面
<h4> Name : {{ researcher }} </h4><br>
<h4> Summary : {{ study }} </h4>
researcher
and study
are not assignment if request method is not POST and form is not valid. 如果请求方法不是POST且表格无效,则study
researcher
和study
人员不分配。 You should define this variable before if statement: 您应该在if语句之前定义此变量:
def about_experiment(request,ex_link_name):
researcher = ''
study = ''
if request.method == 'POST':
...
in else part of views.py you mentioned researcher variable in render method that is producing this error. 在views.py的其他部分中,您提到了在render方法中产生此错误的研究员变量。
so please add 所以请加上
researcher = None
before if statement 在if语句之前
and also add 并添加
study = None
that will also create same error 这也会产生相同的错误
forms.py 表格
from django import forms
from .models import AboutHelp
class AboutHelpForm(forms.ModelForm):
class Meta:
model = AboutHelp
fields = '__all__'
views.py views.py
def about_experiment(request,ex_link_name):
researcher = None
study = None
form = AboutHelpForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
form.save()
return render(request, 'about_experiment.html', {'researcher': researcher, 'study': study})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.