user1328021
user1328021

Reputation: 9840

Messages in Django (updated from 1.2 to 1.4)

I recently updated to Django 1.4 from 1.2.

In the transition the set_messages was deprecated and now the messages API has changed to add_message. Based on this page I should be using the following format:

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

However, I'm getting the error global name 'request' is not defined. Anyone know why?

Here's my code (the line causing the problem in bold)

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:

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

Upvotes: 2

Views: 584

Answers (1)

bradley.ayers
bradley.ayers

Reputation: 38382

Django forms don't have access to the current request. This is an intentional design decision to reduce coupling between components, but comes at the cost of convenience.

As such, you get a NameError because there is no request variable in scope. If you want to use the request within save(), you'll need to pass it in at some point, e.g.

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

# view
form.save(request)

Upvotes: 5

Related Questions