表单不在Django中验证

时间:2015-02-20 12:52:49

标签: django forms validation

我的表格如下所示。 当我单击“添加”按钮而不是通知需要字段时,我收到错误:

DoesNotExist at /users/add-to-group/
Group matching query does not exist.

我的表单代码

class AddUserToGroupForm(forms.ModelForm):
    group = forms.ModelChoiceField(queryset=Group.objects.all(), required=True)
    user = forms.ModelChoiceField(queryset=User.objects.all(), required=True)

    class Meta:
        model = User
        fields = ['group', 'user']

    def has_group(self, user, group_name):
        group1 = Group.objects.get(name=group_name)
        return True if group1 in user.groups.all() else False

    def clean(self):
        cleaned_data = super(AddUserToGroupForm, self).clean()
        g = Group.objects.get(name=cleaned_data.get('group'))
        g.user_set.add(cleaned_data.get('user'))
        if self.has_group(cleaned_data.get('user'), cleaned_data.get('group')):
            self.add_error('user', "This user is already in group.")
        return cleaned_data

1 个答案:

答案 0 :(得分:2)

cleaned_data包含Group个实例,而不是Group的名称。所以你不应该使用这个查询:

Group.objects.get(name=cleaned_data.get('group'))

只需将组实例分配给g变量:

g = cleaned_data.get('group')

has_group函数中存在同样的问题。 group_name参数是Group。代码应该是:

def has_group(self, user, group):
    return group in user.groups.all()

更新:如果用户未在表单上选择任何组或用户,则cleaned_data不包含group / user值。因此,您必须使用clean()方法检查此案例:

def clean(self):
    cleaned_data = super(AddUserToGroupForm, self).clean()
    group = cleaned_data.get('group')
    user = cleaned_data.get('user')
    if group and user:
        if self.has_group(user, group)):
            self.add_error('user', "This user is already in group.")
    return cleaned_data

并且您不应在group.user_set.add(user)中致电clean()。必须从表单的save()方法调用此调用。