未定义全局名称“请求”:覆盖form_valid

时间:2015-01-09 06:11:43

标签: python django django-forms django-views

我有一个UpdateView,我将覆盖form_valid方法。出于某种原因,请求'显示为未在重写方法中定义。这是完整的课程:

 class UpdateTopic(UpdateView):
        model = Post
        slug_field = 'pk'
        slug_url_kwarg = 'pk'
        form_class = CommentForm
        template_name = "forums/update_topic.html"

        def form_valid(self, form): 
            user = self.request.user 
            rep = self.request.user.player.get_rep_total

            # protect the system against url input attacks
            if user == self.object.user or rep >=2500:
                self.object = form.save(commit=False)
                self.object.updated_by = self.request.user 
                self.object.save()
                messages.add_message(request, message.SUCCESS, "<strong>Success:</strong> The comment was edited successfully!")
            else:
                messages.add_message(request, message.ERROR, "<strong>Failed:</strong> You don't have the access level to edit that post!")

问题是行messages.add_message(request, message.SUCCESS, "<strong>Success:</strong> The comment was edited successfully!") 似乎request超出了范围。它为什么这样做?有办法解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

应该是self.request而不是request

messages.add_message(self.request, message.ERROR, "...")