Je reçois UnboundedLocalError dans django. Valeur d'exception: variable locale 'comment_form' réfréné avant l'affectation.UnboundedLocalError dans Django
J'ai utilisé ModelForms à partir de formulaires pour créer un formulaire de commentaire. Il s'agit donc du fichier views.py du formulaire de commentaire.
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})'''
modèle 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')
j'ai vérifié toute la question connexe mais toujours erreur se produit avec ce code. donc pour cette erreur je ne peux pas charger ma page Web
Vous avez un problème d'indentation, la clause else dans la vue doit être un retrait à gauche (et cet appel 'print' ne devrait pas être du tout). –