开发者

Django must be a "User" instance

I get a Must be a User Instance error message.

TRACEBACK

Traceback:
File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response
  92.                 response = callback(request, *callback_args, **callback_kwargs)
File "/Users/ApPeL/Sites/Django/omu2/../omu2/friends/views.py" in add
  13.         if form.is_valid():
File "/Library/Python/2.6/site-packages/django/forms/forms.py" in is_valid
  120.         return self.is_bound and not bool(self.errors)
File "/Library/Python/2.6/site-packages/django/forms/forms.py" in _get_errors
  111.             self.full_clean()
File "/Library/Python/2.6/site-packages/django/forms/forms.py" in full_clean
  234.             value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "/Library/Python/2.6/site-packages/django/forms/widgets.py" in value_from_datadict
  170.         return data.get(name, None)

Exception Type: AttributeError at /friends/add/
Exception Value: 'User' object has no attribute 'get'

views.py

from friends.forms import InviteFriendForm, UserForm
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import Http404, HttpResponseRedirect
from django.contrib.auth.models import User

def add(request, template_name='friends/add.html'):
    if request.method == 'POST':
        from_user = request.user
        user = request.user

        form = InviteFriendForm(UserForm, from_user, user)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')

    else:
        form = InviteFriendForm(UserForm)

    context = { 'form':form, }

    return render_to_response(template_name, context,
        context_instance=RequestContext(request))

forms.py

class UserForm(forms.Form):

    def __init__(self, user=None, *args, **kwargs):
        self.user = user
        super(UserForm, self).__init__(*args, **kwargs)


if EmailAddress:
    class JoinRequestForm(forms.Form):

        e开发者_JS百科mail = forms.EmailField(label="Email", required=True, widget=forms.TextInput(attrs={'size':'30'}))
        message = forms.CharField(label="Message", required=False, widget=forms.Textarea(attrs = {'cols': '30', 'rows': '5'}))

        def clean_email(self):
            # @@@ this assumes email-confirmation is being used
            self.existing_users = EmailAddress.objects.get_users_for(self.cleaned_data["email"])
            if self.existing_users:
                raise forms.ValidationError(u"Someone with that email address is already here.")
            return self.cleaned_data["email"]

        def save(self, user):
            join_request = JoinInvitation.objects.send_invitation(user, self.cleaned_data["email"], self.cleaned_data["message"])
            user.message_set.create(message="Invitation to join sent to %s" % join_request.contact.email)
            return join_request


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})
        self.user.message_set.create(message="Friendship requested with %s" % to_user.username) # @@@ make link like notification
        return invitation


Please try this

def add(request, user_id,template_name='friends/add.html'):
     if request.method == 'POST':
         user = get_object_or_404(User, pk=user_id)

         form = InviteFriendForm(request.user, request.POST)
         if form.is_valid():
             form.save()
             return HttpResponseRedirect('/')

     else:
         form = InviteFriendForm()

     context = { 'form':form, }

     return render_to_response(template_name,
context,
context_instance=RequestContext(request))text_instance=RequestContext(request))

request.user is the sender. and the sender is call in the form. you dont need to declare the from.


In your call:

form = InviteFriendForm(UserForm, from_user, user)

First, the UserForm argument is wrong -- the first argument is expected to be the post data (request.POST).

Second, your InviteFriendForm class doesn't define a constructor (__init__ method). So the arguments aren't passed on to the parent class UserForm. Either define an __init__ method or use keyword arguments, e.g. user=from_user.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜