在赋值django错误之前引用的局部变量

时间:2017-07-02 17:49:44

标签: python django django-models django-forms django-views

这是我的view.py,当我有一个表单,当我提交所需的字段时,它提供了适当的输出但是当我不在表单中输入任何内容并单击提交时,我收到错误说& #34;本地变量'研究员'在分配之前引用"。

此外,我想知道如何将表单数据保存在目标页面上

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})

源页面上的表单是

<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>

表单输出存在的目标页面

<h4> Name : {{ researcher }} </h4><br>
<h4> Summary : {{ study }} </h4>

2 个答案:

答案 0 :(得分:2)

如果请求方法不是POST且表单无效,则

researcherstudy不是赋值。您应该在if语句之前定义此变量:

def about_experiment(request,ex_link_name):
    researcher = ''
    study = ''
    if request.method == 'POST':
    ...  

答案 1 :(得分:1)

在views.py的else部分中,您在render方法中提到了生成此错误的研究者变量。

所以请添加

researcher = None
在if语句之前

并添加

study = None

也会产生同样的错误

<强> forms.py

from django import forms
from .models import AboutHelp

    class AboutHelpForm(forms.ModelForm):
        class Meta:
            model = AboutHelp
            fields = '__all__'

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})