Django DetailView的形式进行评论 [英] Django DetailView with form for comments

查看:669
本文介绍了Django DetailView的形式进行评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  url(r'^ article /(?P< slug> [ -  \ w] +)/ $',views.ArticleView.as_view(),name ='article-detail'),

和我有这样的观点:$ b​​
$ b pre $ class $ ArticleView(DetailView):
model = Article
template_name ='template / article.html'
context_object_name ='article'
$ b $ def get_context_data(self,** kwargs):
context = super(ArticleView,self)。 get_context_data(** kwargs)
context ['comments'] = self.object.comment_set.filter(approved = True)
返回上下文

我已经显示了所有批准的评论(如您所见),但我不知道如何在该文章视图中创建评论表单。
我有这个 ModelForm

  class CommentForm .ModelForm):
class Meta:
model = Comment
fields ='__all__'

和...评论模型:

  class评论(models.Model):
作者= models.CharField(max_length = 100)
article = models.ForeignKey(Article,on_delete = models.CASCADE)
email = models.EmailField()
message = models.TextField(max_length = 1000)
created_at = models.DateTimeField(auto_now_add = True)
approved = models.BooleanField(default = False)

CommentForm的问题是我不知道如何'隐藏'文章和批准的字段以及如何使用ArticleView中获得的文章填充文章字段。



我尝试将 FormMixin DetailView 结合,但是当我提交
评论表单,控制台显示: Me thod not Allowed(POST)
如何创建一个到ArticleView的表单视图?



如果你没有得到什么,请问我,我知道我的语法不好。我会尽量做到尽量清楚。



预先感谢您的解答。

解决方案

  class ArticleView(FormMixin,DetailView):
model = Article
template_name ='template / article.html'
form_class = CommentForm
$ b $ def get_success_url(self):
return reverse('article-detail' ,kwargs = {'slug':self.object.slug})

def get_context_data(self,** kwargs):
context = super(ArticleView,self).get_context_data(** kwargs)
context ['form'] = CommentForm(initial = {
'article':self.object
})
context ['comments'] = self.object。 comment_set.filter(approved = True)
返回上下文
$ b $ def post(self,request,* args,** kwargs):
self.object = self.get_object()
form = self.get_form()

if fo rm.is_valid():
返回self.form_valid(表单)
else:
返回self.form_invalid(表单)
$ b $ def form_valid(self,form):
form.save()
return super(ArticleView,self).form_valid(form)

forms.py

  class CommentForm(forms .ModelForm):
class Meta:
model = Comment'$ b $ exclude =('admit',)
widgets = {$ b $'article':forms.HiddenInput()
}

唯一的方法是我可以...为该文章字段设置一个值(这是文章的外键)是在ArticleView中设置初始值。



如果有人有更好的选择,我很高兴看到它。

>

I have this url mapping:

url(r'^article/(?P<slug>[-\w]+)/$', views.ArticleView.as_view(), name='article-detail'),

and I have this view:

class ArticleView(DetailView):
    model = Article
    template_name = 'template/article.html'
    context_object_name = 'article'

    def get_context_data(self, **kwargs):
        context = super(ArticleView, self).get_context_data(**kwargs)
        context['comments'] = self.object.comment_set.filter(approved=True)
        return context

I've already displayed all the approved comments (as you see), but I don't know how to create a comment form inside that ArticleView. I have this ModelForm:

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = '__all__'

and... Comment model:

class Comment(models.Model):
    author = models.CharField(max_length=100)
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    email = models.EmailField()
    message = models.TextField(max_length=1000)
    created_at = models.DateTimeField(auto_now_add=True)
    approved = models.BooleanField(default=False)

The problem with CommentForm is that I don't know how to 'hide' article and approved fields and how to fill article field with the article got in the ArticleView.

I've tried to combine FormMixin with DetailView but.. when I submit the comment form, console displays: Method not Allowed (POST). How can I create a form view into ArticleView?

If you didn't get something, please ask me, I know my grammar is bad. I will try to be clear as much as possible.

Thanks in advance for answers.

解决方案

I solved it, kind of..

class ArticleView(FormMixin, DetailView):
    model = Article
    template_name = 'template/article.html'
    form_class = CommentForm

    def get_success_url(self):
        return reverse('article-detail', kwargs={'slug': self.object.slug})

    def get_context_data(self, **kwargs):
        context = super(ArticleView, self).get_context_data(**kwargs)
        context['form'] = CommentForm(initial={
            'article': self.object
        })
        context['comments'] = self.object.comment_set.filter(approved=True)
        return context

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        form = self.get_form()

        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def form_valid(self, form):
        form.save()
        return super(ArticleView, self).form_valid(form)

in forms.py:

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        exclude = ('admitted',)
        widgets = {
            'article': forms.HiddenInput()
        }

The only way I could... set a value for that article field (which is a foreign key for the article) was to set initial value in ArticleView.

If someone have a better alternative, I'm glad too see it.

这篇关于Django DetailView的形式进行评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆