[英]Adding a comment for a blog post using UpdateView
假设我有一个博客条目,URL为/blog/1
,现在我想在博客文章中发表评论,因此我单击url /comment/1
。 在Django中, urls.py
看起来像
urlpatterns = (
url(r'^blog/(?P<pk>[0-9])',BlogView.as_view())
url(r'^comment/(?P<pk>[0-9])',CommentView.as_view()
)
和models.py
就像
class Blog(models.Model):
text = models.TextField()
class Comment(models.Model):
comment_text = models.TextField()
for_blog = models.ForeignKey(Blog)
所以现在我在forms.py
有一个forms.py
class CommentForm(forms.ModelForm):
for_blog = forms.IntegerField(required=True)
def __init__(self, blog, *args, **kwargs):
.
.
class Meta:
model=Comment
问题是,如何在Django的UpdateView中实现此功能? 特别是,我希望for_blog
中的for_blog预先填充BlogID
以便可以更轻松地使用它。
我会使用一个表单集( https://docs.djangoproject.com/en/dev/topics/forms/formsets/ )。 然后,您可以使用pk加载博客对象,并将其作为instance kwarg
集中的instance kwarg
传递。 然后,只需在模板中呈现表单集,即可获得相关的博客注释。
还允许添加/删除注释和方便的表单管理的简便方法。
要回答您的实际问题,要使用CommentForm,请在Meta类中定义字段(您不需要其他任何内容):
class CommentForm(forms.ModelForm):
class Meta:
model=Comment
fields = ['for_blog']
然后在您看来,执行以下操作:
class ClassView(UpdateView):
def get(self, request, pk, ...):
blog = get_object_or_404(Blog, pk)
forms = [CommentForm(instance=comment) for comment in blog.comment_set.all()]
return render(request, 'template.html', {'forms': forms})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.