重复的表单字段输入Django

时间:2017-02-23 03:59:35

标签: django validation django-forms django-validation

我们假设我有两个名为Member1Member2的字段,这两个字段属于同一个Classtable。用户将通过ModelForm将值输入这两个字段。如何确保这两个字段不是彼此重复的。这是我目前的验证码:

def clean(self):
    member1 = User.objects.filter(username__iexact=self.Member1.lower())
    member2 = User.objects.filter(username__iexact=self.Member2.lower())

    if member2 == member3:
        raise  ValidationError("Can't have duplicate team members")

但它不起作用, 有什么想法吗?

View.py

        if request.method == 'POST':
            form = CreateTeamForm(request.POST, request.FILES)
            if form.is_valid():
                instance = form.save(commit=False)
                instance.team_creator = request.user.id
                p2=None
                p3=None
                p4=None
                if instance.team_member2:
                    instance.team_member2 = User.objects.values('id').filter(username=instance.team_member2)[0]['id']
                    p2 = Profile.objects.get(user_id=instance.team_member2)
                    p2.team_id = instance.Team_ID
                    p2.save()
                if instance.team_member3:
                    instance.team_member3 = User.objects.values('id').filter(username=instance.team_member3)[0]['id']
                    p3 = Profile.objects.get(user_id=instance.team_member3)
                    p3.team_id = instance.Team_ID
                    p3.save()
                if instance.team_member4:
                    instance.team_member4 = User.objects.values('id').filter(username=instance.team_member4)[0]['id']
                    p4 = Profile.objects.get(user_id=instance.team_member4)
                    p4.team_id = instance.Team_ID
                    p4.save()

                instance.save()

1 个答案:

答案 0 :(得分:0)

您应该从Member1属性获取Member2cleaned_data

def clean(self):
    data = self.cleaned_data
    member1 = User.objects.filter(username__iexact=data['Member1'].lower())
    member2 = User.objects.filter(username__iexact=data['Member2'].lower())

    if member1 == member2:
        raise  ValidationError("Can't have duplicate team members")

    return data