global name 'request' is not defined: overriding form_valid

夙愿已清 提交于 2019-12-12 03:16:33

问题


I have an UpdateView which I am overriding the form_valid method. For some reason 'request' is shown as being not defined within the overridden method. Here is the full class:

 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!")

The problem is the line messages.add_message(request, message.SUCCESS, "<strong>Success:</strong> The comment was edited successfully!") It seems like the request is out of scope some how. Why is it doing this? Is there a way to get around this?


回答1:


It should be self.request and not request.

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


来源:https://stackoverflow.com/questions/27854814/global-name-request-is-not-defined-overriding-form-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!