如何修复“ NameError:未定义名称'context'”

时间:2019-09-02 01:43:47

标签: python django django-class-based-views

我想在博客应用程序的评论和回复部分中使用ajax。在基于函数的视图中,一切工作正常,但我想基于类的视图进行操作。

***My function based view***
def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    comments = Comment.objects.filter(post=post, reply=None).order_by('-id')
    if request.method == 'POST':
        comment_form = CommentForm(request.POST or None)
        if comment_form.is_valid():
            content = request.POST.get('content')
            reply_id = request.POST.get('comment_id')
            comment_qs = None
            if reply_id:
                comment_qs = Comment.objects.get(id=reply_id)

            comment = Comment.objects.create(post=post,
                                             user=request.user,
                                             content=content,
                                             reply=comment_qs)
            comment.save()

    else:
        comment_form = CommentForm()
    context = {
        'title': 'blog',
        'post': post,
        'comments': comments,
        'comment_form': comment_form,
    }
    if request.is_ajax():
        html = render_to_string('blog/comments.html', context, request=request)
        return JsonResponse({'form': html})

    return render(request, 'blog/post_detail.html', context)

***My class based view***
class PostDetailView(FormMixin, DetailView):
    model = Post
    form_class = CommentForm

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        post = get_object_or_404(Post, id=self.object.id)
        comments = Comment.objects.filter(post=post, reply=None).order_by('-id')
        context['title'] = 'Blog Detail'
        context['comments'] = comments
        context['comment_form'] = self.get_form()
        return context

    def post(self, request, *args, **kwargs):
        #if request.user.is_authenticated():

        self.object = self.get_object()
        form = self.get_form()
        if form.is_valid():
            content = request.POST.get('content')
            reply_id = request.POST.get('comment_id')
            comment_qs = None
            if reply_id:
                comment_qs = Comment.objects.get(id=reply_id)
            comment = Comment.objects.create(post=self.object,
                                             user=request.user,
                                             content=content,
                                             reply=comment_qs)
            comment.save()
            #return HttpResponseRedirect(self.object.get_absolute_url())
        else:
            return self.form_invalid(form)

        if request.is_ajax():
            html = render_to_string('blog/comments.html', context, request=request)
            return JsonResponse({'form': html})

    def get_success_url(self):
        return reverse('post-detail', kwargs={'pk': self.kwargs['pk'], })

在我基于班级的视图中,if request.is_ajax(): html = render_to_string('blog/comments.html', context,request=request) return JsonResponse({'form': html}) 部分显示未定义上下文的错误。那么既然我已经有了上下文,那么如何解决此问题或如何将其包含在函数中。 我的基于函数的视图代码没有问题,它按预期运行。

2 个答案:

答案 0 :(得分:0)

在这种方法中:

def post(self, request, *args, **kwargs):
        ...
        ...

        if request.is_ajax():
            html = render_to_string('blog/comments.html', context, request=request)
            return JsonResponse({'form': html})

简单,您使用上下文,但未定义上下文。要么将其作为参数传递,要么将其定义为变量

答案 1 :(得分:0)

是因为。您使用了上下文变量,但尚未定义。

if request.is_ajax():
    html = render_to_string('blog/comments.html', context, request=request)
    return JsonResponse({'form': html})

尝试此操作以获得上下文:

context = self.get_context_data(object=self.object)

通过跟踪DetailView的源代码可以看到这一点,您会看到DetailView从BaseDetailView继承而来,您将找到此脚本来获取上下文

希望这对您有所帮助!