所以我有一个模型文件,一个forms.py文件和一个views.py文件。 views文件返回帖子的详细视图,现在我希望在详细视图中添加注释模型的模型形式,以便可以在d模板中以{{form}}的形式访问它。我可以使用基于函数的视图来做到这一点,但是发现使用基于类的视图很难做到。这是代码。
#models.py
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=50)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
date_posted = models.DateTimeField(default=timezone.now)
likes = models.ManyToManyField(User, blank=True, related_name='post_likes')
image = models.ImageField(null=False, blank=False, upload_to='post_images')
slug = models.SlugField(unique=True)
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
text = models.CharField(max_length=150)
date_commented = models.DateTimeField(auto_now_add=True)
comment_by = models.ForeignKey(User, on_delete=models.CASCADE)
#forms.py
from django import forms
from users.models import Profile
from Post.models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['text', ]
#views.py
from django.views.generic import ListView, DetailView
class PostDetail(DetailView):
model = Post
template_name = 'Post/blog-detail.html'
希望我的问题有意义,谢谢。
答案 0 :(得分:0)
您可以这样做,例如:
class PostDetail(DetailView):
model = Post
template_name = 'Post/blog-detail.html'
def get_context_data(self, **kwargs):
context = super(PostDetail, self).get_context_data(**kwargs)
context['comment_form'] = CommentForm()
return context