我想添加在同一个html页面中添加注释的功能,该详细信息从基于此类的视图开始。 我还剩下要使用的模型和html模板。 请帮助我
我想用作起点的基于类的视图:
class PostDetailView(DetailView):
model = Post
模型:
class Comments(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
content = models.TextField()
date_added = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.content
html模板:
<div id="comments">
<h3>{{ comments.total }}</h3>
<ol class="commentlist">
{% for comment in comments %}
<li class="depth-1">
<div class="avatar">
<img width="50" height="50" alt=""
src="{{ comment.user.profile.image.url }}"
class="avatar">
</div>
<div class="comment-content">
<div class="comment-info">
<cite>{{ comment.user }}</cite>
<div class="comment-meta">
<time datetime="2014-07-12T23:05"
class="comment-time">{{ comment.date_added|date:"F d, Y" }}</time>
</div>
</div>
<div class="comment-text">
<p>{{ comment.content }}</p>
</div>
</div>
</li>
{% endfor %}
</ol> <!-- /commentlist -->
<!-- respond -->
<div class="respond">
<h3>Leave a Comment</h3>
<!-- form -->
<form action="" method="POST">
{% csrf_token %}
<fieldset>
<div class="group">
{{ form|crispy }}
<button class="submit full-width" type="submit">Add Comment</button>
</div>
</fieldset>
</form> <!-- /contactForm -->
</div> <!-- /respond -->
</div> <!-- /comments -->
答案 0 :(得分:0)
重写DetailView的get_context_data方法以通过上下文传输注释。在您的类PostDetailView中添加此方法。
def get_context_data(self, **kwargs):
context = {}
if self.object:
context['object'] = self.object
context['comments']=Comments.objects.all() #modify this queryset according to how you want to display comments
context.update(kwargs)
return super().get_context_data(**context)
比模板中的您可以包含这段代码
{% for comment in comments%}
<div>
{{comment}}
</div>
{% endfor %}
并在forms.py
中获取评论from django import forms
from .models import Comments
class CommentForm(forms.Form):
class Meta:
model = Comments
fields = [] #mention fields of comments u want to render in form
您必须将FormView和DetailView一起扩展,因为DetailView的主体有post方法要覆盖。
所以在views.py中:
from .forms imoprt CommentForm
from django.views.generic.edit import FormView
class PostDetailView(DetailView, FormView):
model = Post
form_class = CommentForm
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
#do what you want with data
我建议您遍历类的方法以覆盖它们。FormView