我在django中遇到UnboundedLocalError。 异常值:在赋值之前引用局部变量'comment_form'。Django中的UnboundedLocalError
我使用FormForms从窗体创建评论窗体。所以这是评论窗体的views.py文件。
def post_detail(request,year,month,day,post):
'''post=get_object_or_404(Post,slug=post,status='published',publish__year=year,
publish__month=month,publish__day=day)'''
try:
post=Post.published.get(slug=post)
except Post.DoesNotExist:
raise Http404("Post Doesnot Exist")
#list of active comments for the post
comments=post.comments.filter(active=True)
if request.method=='POST':
#a comment was posted
comment_form=CommentForm(data=request.POST)
if comment_form.is_valid():
#create comment object but dont save to database yet
new_comment=comment_form.save(commit=False)
#assign the current post to the comment
new_comment.post=post
#save the comment to database
new_comment.save()
else:
print (form.error)
comment_form=CommentForm()
return render(request,'blog/post/detail.html',{'post':post,'comments':comments,'comment_form':comment_form})
'''return render(request,'blog/post/detail.html',{'post':post})'''
模板detail.html
{% extends "blog/base.html" %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
<h1>{{ post.title }}</h1>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|linebreaks }}
(% with comments.count as total_comments %}
<h2>
{{total_comments}}comment{{total_comments|pluralize}}
</h2>
{% endwith %}
{% for comment in comments %}
<div class="comment">
<p class="info">
Comment {{forloop.counter }} by {{comment.name}}
{{comment.created}}
</p>
{{comment.body|linebreaks}}
</div>
{%empty%}
<p>There are nocomments yet.</p>
{% endfor %}
{% if new_comment %}
<h2>Your comment has been added.</h2>
{% else %}
<h2>Add a new comment.</h2>
<form action="." method="post">
{{comment_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Add comment"></p>
</form>
{% endif %}
{% endblock %}
forms.py
from django import forms
from .models import Comment
class EmailPostForm(forms.Form):
name=forms.CharField(max_length=25)
email=forms.EmailField()
to=forms.EmailField()
comments=forms.CharField(required=False,widget=forms.Textarea)
class CommentForm(forms.ModelForm):
class Meta:
model=Comment
fields=('name','body')
我检查了所有相关的问题,但与此代码仍然出现错误。 因此对于此错误我无法加载我的网页
你有一个缩进问题,视图中的else子句应该是一个向左缩进(并且'print'调用应该不存在)。 –