DetailView中的Django ModelForm

时间:2015-07-27 21:13:13

标签: python django django-forms

我有一个显示Post的DetailView。我现在想要添加为Comment创建Post的功能。为此,我需要在CommentFormDetailView,以便我可以使用Post在同一页面上创建评论。

这是可能的,还是我应该寻找另一种方法,比如“手动”处理表单?

class Comment(models.Model):
    body = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    author_name = models.CharField(max_length=255)
    parent_post = models.ForeignKey('Post',related_name='comments')

class PostDetailView(BlogMixin,DetailView):
    """ A view for displaying a single post """
    template_name = 'post.html'
    model = Post
    #Add some code for the CommentForm here?

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        exclude = ("parent_post","created_at")

    def create_view(request, **kwargs):
        if request.method == "POST":
            parent_fk = request.args['parent_fk'] #Im hoping to find how this will work soon 
            form = CommentForm(request.POST)
            if form.is_valid():
                new_comment = form.save(commit=False)
                new_comment.parent_post = parent_fk
                new_comment.save()
                return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

**替代**

我一直在尝试应用解决方案 - A better alternative - 但我得到了

Exception Value: __init__() takes exactly 1 argument (3 given)
Exception Location: .../sitepackages/django/core/handlers/base.py in get_response, line 112

并且还无法追踪它。

class PostView(BlogMixin,DetailView):
    """ A view for displaying a single post """
    template_name = 'post.html'
    model = Post
    def get_context_data(self, **kwargs):
        context = super(PostView, self).get_context_data(**kwargs)
        context['form'] = CommentForm()
        return context

class PostDetailView(View):

    def get(self, request, *args, **kwargs):
        view = PostView.as_view()
        return view(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        view = PostComment.as_view()
        return view(request, *args, **kwargs)

class PostComment(  SingleObjectMixin , FormView):
    template_name = 'post.html'
    form_class = CommentForm
    model = Post

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        return super(PostComment, self).post(request, *args, **kwargs)

    def get_success_url(self):
        return reverse('post-detail', kwargs={'pk': self.object.pk})
class BlogMixin(object):
    """
    Basic mixin for all the views. Update the context with additional
    information that is required across the whole site, typically
    to render base.html properly
    """
    def get_context_data(self, *args, **kwargs):
        context = super(BlogMixin, self).get_context_data(*args, **kwargs)
        blog = Blog.get_unique()
        context.update({
            'blog': blog,
            'active_user': users.get_current_user(),
            'is_admin': users.is_current_user_admin()
        })
        return context

urls.py:     url(r'^ post /(?P [\ d] +)/ $',views.PostDetailView。,name =“post-detail”),

3 个答案:

答案 0 :(得分:1)

如果您想使用第一种方法,可以将FK设为隐藏字段。在您的视图中,您可以在将注释提交到数据库之前保存FK。像这样:

if form.is_valid():
    comment = form.save(commit=False)
    comment.parent_post = parent_post
    comment.save()

编辑:如果您想要提取评论,那么您可以使用过滤过滤来获取评论的QuerySet。

答案 1 :(得分:0)

最后我无法使用重定向,但以下工作正常:

class PostDetailView(BlogMixin,CreateView):
    """ A view for displaying a single post """
    template_name = 'post.html'
    model = Comment
    fields = ['body','author_name'] 
    def get_context_data(self, **kwargs):

        context = super(PostDetailView, self).get_context_data(**kwargs)
        context['post'] =  Post.objects.get(pk=self.kwargs['pk'])
        return context

    def form_valid(self, form):
        # self.object = form.save()
        obj = form.save(commit=False)
        obj.parent_post = Post.objects.get(pk=self.kwargs['pk'])
        obj.save()

        return redirect('post-detail', self.kwargs['pk'])

答案 2 :(得分:0)

为什么不在详情视图的上下文中发送表单:

class YourDetailView(DetailView):
    #Your stuff here
    def get_context_date(self, **kwargs):
         context = super(YOurDetailView, self).get_context_data(**kwargs)
         context['form'] = YourForm
         return context

PS。在get_context_date中查找参数..