gpt4 book ai didi

django - Django 中的消息(从 1.2 更新到 1.4)

转载 作者:行者123 更新时间:2023-12-02 22:22:39 25 4
gpt4 key购买 nike

我最近从 1.2 更新到 Django 1.4。

在转换过程中,set_messages 被弃用,现在消息 API 已更改为 add_message。基于this page我应该使用以下格式:

messages.add_message(request, messages.INFO, 'Hello world.')

但是,我收到错误 global name 'request' is not defined。有人知道为什么吗?

这是我的代码(导致问题的行以粗体显示)

class InviteFriendForm(UserForm):

to_user = forms.CharField(widget=forms.HiddenInput)
message = forms.CharField(label="Message", required=False, widget=forms.Textarea(attrs = {'cols': '20', 'rows': '5'}))

def clean_to_user(self):
to_username = self.cleaned_data["to_user"]
try:
User.objects.get(username=to_username)
except User.DoesNotExist:
raise forms.ValidationError(u"Unknown user.")

return self.cleaned_data["to_user"]

def clean(self):
to_user = User.objects.get(username=self.cleaned_data["to_user"])
previous_invitations_to = FriendshipInvitation.objects.invitations(to_user=to_user, from_user=self.user)
if previous_invitations_to.count() > 0:
raise forms.ValidationError(u"Already requested friendship with %s" % to_user.username)
# check inverse
previous_invitations_from = FriendshipInvitation.objects.invitations(to_user=self.user, from_user=to_user)
if previous_invitations_from.count() > 0:
raise forms.ValidationError(u"%s has already requested friendship with you" % to_user.username)
return self.cleaned_data

def save(self):
to_user = User.objects.get(username=self.cleaned_data["to_user"])
message = self.cleaned_data["message"]
invitation = FriendshipInvitation(from_user=self.user, to_user=to_user, message=message, status="2")
invitation.save()
if notification:
notification.send([to_user], "friends_invite", {"invitation": invitation})
notification.send([self.user], "friends_invite_sent", {"invitation": invitation})
**messages.add_message(request, messages.SUCCESS, "Friendship requested with %s" % to_user.username)**
return invitation

回溯:

Traceback:
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/nb/Desktop/nutstore/apps/profiles/views.py" in profile
125. invite_form.save()
File "/Users/nb/Desktop/nutstore/apps/friends/forms.py" in save
81. messages.add_message(request, messages.SUCCESS, "Friendship requested with %s" % to_user.username)

Exception Type: NameError at /profiles/profile/test/
Exception Value: global name 'request' is not defined

最佳答案

Django 表单无权访问当前请求。这是一个有意的设计决策,旨在减少组件之间的耦合,但以便利为代价。

因此,您会得到一个 NameError,因为范围内没有请求变量。如果您想在 save() 中使用请求,您需要在某个时候将其传入,例如

class InviteFriendForm(forms.Form):
def save(self, request):
# ...

# view
form.save(request)

关于django - Django 中的消息(从 1.2 更新到 1.4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13466179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com