2010-07-01 52 views
1

在我的應用程序中,我有一個名爲UserProfile的擴展用戶模型。此用戶最多可以添加4個好友模型。每個添加好友都與UserProfile相關聯1對1。在我的AddFriend表單中,我有一個自定義清理方法,用於pid字段(個人id)。這個clean_pid應該檢查給定pid的用戶是否已經註冊/添加爲朋友並返回適當的ValidationError。 (在朋友表中沒有實例)提交表單我收到後:使用自定義清理方法時DoesNotExist異常

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

回答

1

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

它是因爲您試圖獲取UserProfile對象,但檢查User對象DoesNotExists而不是UserProfile。

+0

該死的,那一定是因爲這股熱浪的... – crivateos 2010-07-01 20:45:07

1

更改此:except User.DoesNotExist:這樣:except UserProfile.DoesNotExist: