Django必须是“用户”实例

时间:2010-10-01 11:07:20

标签: django django-forms django-views

我得到一个必须是用户实例的错误消息。

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):

        email = 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

2 个答案:

答案 0 :(得分:3)

请试试这个

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是发件人。并且发件人在表单中呼叫。你不需要申报来自。

答案 1 :(得分:1)

在你的电话中:

form = InviteFriendForm(UserForm, from_user, user)

首先,UserForm参数是错误的 - 第一个参数应该是后期数据(request.POST)。

其次,您的InviteFriendForm类没有定义构造函数(__init__方法)。因此参数不会传递给父类UserForm。定义__init__方法或使用关键字参数,例如user=from_user