MultipleObjectsReturned at ... get()返回多个Person - 它返回2

时间:2016-11-17 08:38:03

标签: django forms error-handling

我正在使用这些模型:

class Person(models.Model):    
    name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)
    name_in_bangla = models.CharField(max_length=100)
    nick_name = models.CharField(max_length=30)
    birth_date = models.DateField()
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        related_name='member_persons')

    class Meta:
        ordering = ['name']
        unique_together = ['name', 'birth_date']

我的观点:

class PersonCreate(SuccessMessageMixin,CreateView):
    model = Person
    form_class = MemberForm
    success_message = "%(name)s was added as %(category)s successfully."

    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        form.request = self.request
        return form

我的观点:

class MemberForm(ModelForm):

    class Meta:
        model = Person
        exclude =('user',)

    def clean(self):
        user = get_user(self.request)
        name = self.cleaned_data.get('name')
        birth_date = self.cleaned_data.get('birth_date')
        if self.instance.id:
            if Person.objects.filter(user=user).exclude(id=self.instance.id).exists():
                self.add_error('name', "You already submitted data")
            elif Person.objects.filter(name=name, birth_date=birth_date).exclude(id=self.instance.id).exists():
                self.add_error('name', "Person with this Name and Birth date already exists.")
        else:
            if Person.objects.filter(user=user).exists():
                self.add_error('name', "You already submitted data")
            elif Person.objects.filter(name=name, birth_date=birth_date).exists():
                self.add_error('name', "Person with this Name and Birth date already exists.")
        return self.cleaned_data

    def save(self, commit=True):
        person = super().save(commit=False)
        if not person.pk:
            person.user = get_user(self.request)
        if commit:
            person.save()
            self.save_m2m()
        return person

它适用于不同的人。但是当我尝试为人使用相同的名字但是出生日期不同时,它给出了带有'get()的MultipleObjectReturn多个人 - 它返回了2个!'

但是我使用了unique_together = ['name','birth_date']约束以及我使用clean方法来捕获表单中的约束错误。但我的表单没有捕获MultipleObjectReturned错误。

我怎样才能在表单中捕获这些错误?我的代码做错了什么。任何机构建议将不胜感激。

我的其他观点:

class PersonDetailView(generic.DetailView):

    queryset = (
         Person.objects.all()
        .prefetch_related('child_set')
         # below omitted because of with tag
        # and conditional display based on time
        # .prefetch_related('blog_posts')
     )
class PersonUpdate(SuccessMessageMixin,UpdateView):

    model = Person
    form_class = MemberForm
    success_message = "%(category)s: %(name)s was updated successfully."

    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        form.request = self.request
        return form


@require_authenticated_permission(
'member.delete_person')
class PersonDelete(DeleteView):
    model = Person
    success_url = '/allmember/'

    success_message = "%(category)s: %(name)s was deleted successfully."


    def delete(self, request, *args, **kwargs):
        messages.success(self.request, self.success_message)
        return super(PersonDelete, self).delete(request, *args, **kwargs)

1 个答案:

答案 0 :(得分:0)

看起来你有两个用户使用相同的slug。如果你的网址(你没有显示)是/person/<slug>/,那么你需要为你的slug字段设置unique=True