问题
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