2012-05-19 54 views
0

我有一個奇怪的謎語解決:Django的:「UserProfileRole.userProfile」必須是一個「用戶配置」實例

我伸出我的Django 1.4用戶對象與用戶配置,如在https://docs.djangoproject.com/en/dev/topics/auth/描述,並希望實施項目特定的角色。所以,我的模型如下所示:

class UserProfile(models.Model): 
    user = models.ForeignKey(User, unique=True) 
    projects = models.ManyToManyField(Project, through='UserProjectRole') 
    [...] 

class UserProjectRole(models.Model): 
    userProfile = models.ForeignKey(UserProfile) 
    project = models.ForeignKey(Project) 
    group = models.ForeignKey(Group) 
    [...] 

我需要傳遞一個CSS類,所以我創建了一個模型的形式UserProjectRole並與小部件實現USERPROFILE場:

class ProjectRoleForm(forms.ModelForm): 
    userProfile = forms.ModelMultipleChoiceField(label='Users', 
     queryset=UserProfile.objects.all(), 
     widget=forms.SelectMultiple(attrs={'class': 'select-multiple'})) 

    class Meta: 
     model = UserProjectRole 

表單呈現正確,但是,它在保存過程中崩潰,出現以下錯誤

Cannot assign "[<UserProfile: MyUser>]": "UserProjectRole.userProfile" must be a "UserProfile" instance. 

有沒有人有想法?

回答

3

我的猜測是因爲你正在使用forms.SelectMultiple小部件。它給你用戶配置實例([<UserProfile: MyUser>])的列表,而不是一個單一的用戶配置實例,它是一個ForeignKey的場(UserProjectRole.userProfile)設爲必修課。因此我建議嘗試使用forms.Select小部件。

+0

唉,猜測我犯了一個邏輯錯誤,試圖使用單個實體將許多用戶分配給一個角色。哎唷,我會檢查的。 – PenthousePauper

相關問題