在Django中添加评论

时间:2019-03-16 12:45:26

标签: django django-class-based-views

我是Django的学生和初学者。我只想问一下如何将该注释代码从函数视图转换为类视图。还要注意,这本书有一个很烂的领域。

def BookDetail(request, id):
most_recent = Book.objects.order_by('-timestamp')[:3]
book= get_object_or_404(Book, id=id)
form = CommentForm(request.POST or None)
if request.method == "POST":
    if form.is_valid():
        form.instance.user = request.user
        form.instance.post = book
        form.save()
        return redirect(reverse("book-detail", kwargs={
            'id': book.pk
        }))
context = {
    'form': form,
    'book': book,
    'most_recent': most_recent,

}
return render(request, 'catalog/book_detail.html', context)

从上面的代码到下面的代码:

class BookDetailView(DetailView):
model = Book

1 个答案:

答案 0 :(得分:1)

您可以定义详细信息视图和get_context_data,您可以在其中添加尽可能多的字段以将其传递给模板。

class BookDetailView(DetailView):

    model = Book

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # adding additional field like below
        context['now'] = timezone.now()
        return context