【发布时间】:2021-12-29 14:07:09
【问题描述】:
我是 Django 的新手我开始了一个博客项目我想在我的项目中添加评论部分功能我有一个错误模式表单未在类中定义
view.py
from Blog.models import Comment
from Blog.forms import CommentForm
def post_detail_view(request,year,month,day,post):
post=get_object_or_404(Post,slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
comments=Comment.objects.filter(active=True)
csubmit=False
if request.method=='POST':
form=CommentForm(data=request.POST)
if form.is_valid():
new_comment=form.save(commit=False)
new_comment.post=post
new_comment.save()
csubmit=True
else:
form=CommentForm()
return render(request,'blog/detail.html',{'post':post,'comments':comments,'csubmit':csubmit,'form':form})
如果我尝试运行此功能,我想在详细页面中显示表单,如果最终用户提交表单,则显示同一页面
detail.html
<!doctype html> {% extends "blog/base.html" %} {% block title_block %} detail Page {% endblock%} {% block body_block %}
<h1>This Is Your Content</h1>
<div>
<h2>{{post.title|title}}</h2>
</div>
<div>
{{post.body|title|linebreaks}}
<p>Publised of {{post.publish|title}} Published By {{post.author|title}}</p>
<div>
{% with comments.count as comments_count %}
<h2>{{comments_count}} Comment{{comments_count|pluralize}}</h2>
{% endwith%}
<div>
{%if comments %} {%for comment in comments %}
<p> comment {{forloop.counter}} by {{comment.name}} on {{comment.created}}
</p>
<div class="cb">{{comment.body|linebreaks}}</div>
<hr> {%endfor%} {%else%}
<p>There are NO Comments Yet !!!</p>
{%endif%} {%if csubmit %}
<h2>Your Comment Added Succefully</h2>
{%else%}
<form method="post">
{{form.as_p}} {%csrf_token%}
<input type="submit" name="" value="Submit Comment">
</form>
{%endif%}
</div>
{%endblock%}
在这里我定义了我的表单 forms.py
from Blog.models import Comment
class CommentForm(ModelForm):
class meta:
model=Comment
fields=('name','email','body')
我在下面提到的相关模型 models.py
class Comment(models.Model):
post=models.ForeignKey(Post, related_name=('comments'), on_delete=models.CASCADE)
name=models.CharField( max_length=32)
email=models.EmailField()
body=models.TextField()
created=models.DateTimeField( auto_now_add=True)
updated=models.DateTimeField (auto_now=True)
active=models.BooleanField(default=True)
class meta:
ordering=('-created',)
def __str__(self):
return 'Cammnted by{} on {}'.format(self.name,self.post)
【问题讨论】:
-
您在 forms.py 中缺少
from django.forms import ModelForm
标签: html django django-models jinja2