使用自定义清理方法时,DoesNotExist异常

时间:2010-07-01 20:27:55

标签: django-forms validation

在我的应用程序中,我有一个名为UserProfile的扩展用户模型。此用户最多可以添加4个好友模型。每个添加的朋友与UserProfile相关1对1。在我的AddFriend表单中,我有一个自定义清理方法,用于pid字段(个人ID)。此clean_pid应检查具有给定pid的用户是否已注册/添加为好友并返回正确的ValidationError。提交表单后(朋友表中没有实例)我得到了:

DoesNotExist at /user/add_friend/
UserProfile matching query does not exist.

如果没有匹配发送'pid'的用户,则应返回其值。为什么它不起作用?

追溯:

File "/home/rails/fandrive/site-packages/django/core/handlers/base.py" in get_response
  92.                 response = callback(request, *callback_args, **callback_kwargs)
File "/home/rails/fandrive/site-packages/django/contrib/auth/decorators.py" in __call__
  78.             return self.view_func(request, *args, **kwargs)
File "/home/rails/fandrive/accounts/views.py" in add_friend
  22.         if form.is_valid():
File "/home/rails/fandrive/site-packages/django/forms/forms.py" in is_valid
  120.         return self.is_bound and not bool(self.errors)
File "/home/rails/fandrive/site-packages/django/forms/forms.py" in _get_errors
  111.             self.full_clean()
File "/home/rails/fandrive/site-packages/django/forms/forms.py" in full_clean
  243.                     value = getattr(self, 'clean_%s' % name)()
File "/home/rails/fandrive/accounts/forms.py" in clean_pid
  48.             user = UserProfile.objects.get(pid=self.cleaned_data['pid'])
File "/home/rails/fandrive/site-packages/django/db/models/manager.py" in get
  120.         return self.get_query_set().get(*args, **kwargs)
File "/home/rails/fandrive/site-packages/django/db/models/query.py" in get
  305.                     % self.model._meta.object_name)

模特:

class InheritedProfile(models.Model):
    pid = models.CharField("PID", max_length=11, blank=True, null=True)
(...)
    class Meta:
        abstract=True

class UserProfile(InheritedProfile):
(...)
    user = models.ForeignKey(User, unique=True, related_name='profile')

class Friend(InheritedProfile):
(...)
    friend_of = models.ForeignKey(UserProfile, related_name='friend_of')

表格:

class FriendForm(forms.ModelForm):
    pid = forms.RegexField(regex=r'^\d{11}', max_length=11 ,widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=50)))
(...)    
    class Meta:
        model = Friend
        exclude = ( 'friend_of', )

    def clean_pid(self):
        try:
            user = UserProfile.objects.get(pid=self.cleaned_data['pid'])
        except User.DoesNotExist:
            try:
                user = Friends.objects.get(pid=self.cleaned_data['pid'])
            except Friend.DoesNotExist:
                return self.cleaned_data['pid']
            raise forms.ValidationError(_(u'User is somebody's friend.'))
        raise forms.ValidationError(_(u'User with given PID already registered.'))

    def save(self, user, *args, **kwargs):
        self.instance.friend_of = user                           
        post = super(FriendForm, self).save(*args, **kwargs)
        post.save()
        return post

观点(不确定是否需要):

def add_friend(request):
    userprofile = UserProfile.objects.get(user=request.user)
    count = 0

    if request.method == 'POST':
        form = FriendForm(request.POST, request.FILES,)
        if form.is_valid():
            count = Friend.objects.filter(friend_of=userprofile).count() 
            if not count > 5:
                form.save(user=request.user)            
                next = reverse('user_profile',)
            else:
                msg = "You already have 4 friends"
                render_to_response('user/data_operations/error.html', {'msg': msg}, context_instance=RequestContext(request))
            return HttpResponseRedirect(next)
    else:
        form = FriendForm()
    return render_to_response('user/data_operations/add_friend.html', {
            'form':form, 'user':request.user,
            }, context_instance=RequestContext(request))

2 个答案:

答案 0 :(得分:1)

try: user = UserProfile.objects.get(pid=self.cleaned_data['pid']) except User.DoesNotExist:

这是因为您尝试获取UserProfile对象但检查User对象DoesNotExists,而不是UserProfile。

答案 1 :(得分:1)

将此更改为except User.DoesNotExist:except UserProfile.DoesNotExist: