Django中的局部变量错误

时间:2011-09-04 18:39:47

标签: python django templates

我正在尝试为网页创建评论部分。但是,我在views.py文件中使用的函数返回错误:“赋值前引用的局部变量”。这是代码:

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django import forms
from django.db import models
from django.template import RequestContext




class CommentForm(forms.Form):

    name = forms.CharField(max_length=100)

    email = forms.EmailField(required=False)

    comment = forms.CharField(widget=forms.Textarea)



    def clean_message(self):

        message = self.cleaned_data['message']

        num_words = len(message.split())

        return message



def comment(request):
    commentlist = []

    errors = []

    if request.method == "POST":
        form = CommentForm(request.POST)

        if form.is_valid():
            comment = form.cleaned_data
            commentlist.append(comment)

            return HttpResponseRedirect('')
    else:
        form = CommentForm()    
    initialData = ({'form': form, 'commentlist': commentlist, 'comment': comment})

    csrfContext = RequestContext(request, initialData)

    return render_to_response('hello_world.htm', csrfContext) 

这是我的模板,名为“hello_world.htm”:

<html>
<head>
<style>
ul.errorlist{

margin: 0;

padding: 0;

}



.errorlist li{

background-color: red;

color: white;

display: block;

font-size: 10px;

margin: 0 0 3px;

padding: 4px 5px;

}



.field

{

background-color:#E2F2F2;

border: white 1px solid;

padding: 5px;

width: 80%;

font-family: Arial;

}


.field2

{

background-color:#E2F2E2;

border: white 1px solid;

padding: 5px;

width: 80%;

font-family: Arial;

}


.header

{

background-color:#E2E2F2;

border: white 1px solid;

padding: 5px;

width: 80%;

font-family: Arial;

}

</style>
</head>
<body>
Hello world
<br/>
<br/>
<br/>
<br/>
<div class="field2">
Comments:
</div>
{% for comment in commentlist %}
<div class="field2">
{{ comment }}
</div>
{% endfor %}
{% if form.errors %}

<p style="color: red;"><b>Please correct the error{{ form.errors|pluralize }} below.  </b></p>

{% endif %}
<div class="field"><b>Want to comment?</b></div>

<form action="" method="post">

{% csrf_token %}

<div class="field">

{{ form.name.errors }}

<label for="id_subject">Name:</label>

{{ form.name }}

</div>

<div class="field">

{{ form.email.errors }}

<label for="id_email">Your e-mail address</label>

{{ form.email }}

</div>

<div class="field">

{{ form.comment.errors }}

<p>Comment:</p>

{{ form.comment }}

<br/>

<input type="submit" value="Submit">

</div>

   

如何重写views.py(特别是“注释”功能)以便不会出现此错误?很抱歉,如果我的代码中有很多错误,我只使用了Django几天。谢谢!

1 个答案:

答案 0 :(得分:0)

我看到一个可能未分配的变量,具体取决于 if 语句的触发方式:comment。将其设置为null或启动某些内容:

def comment(request):
    commentlist = []
    comment = ''

并且将函数重命名为其他东西,也许是get_comment() - 让变量与函数同名是个坏主意。

另外,要调试commentlist变量 - 请尝试在 else 语句中设置它,只是为了查看您是否正确处理GET

    else: #form invalid
        commentlist = ['bad form']
else:
    form = CommentForm()
    commentlist = ['testing']

更新 - wups,我刚注意到你在模板字典中同时拥有commentcommentlist。拿出评论:

initialData = ({'form': form, 'commentlist': commentlist}

否则我怀疑它干扰了模板中的comment变量。

更新2 - 叹息。我没有仔细阅读代码 - 在分配HttpResponseRedirect后你有commentlist权限 - 所以列表永远不会被设置并传递给render_to_response。如果您认为commentlist将通过多次调用构建 - 它将不会,因为您在函数开头将其设置为空列表。基本上,您需要重新编写所有逻辑。 :)

或者您可以尝试评论HttpResponseRedirect,然后让它落到render_to_response行。

相关问题