使用自定义清理方法

时间:2016-11-06 07:30:09

标签: django forms view

我的模特形式:

class MemberForm(ModelForm):
    birth_date = forms.DateField(widget=forms.widgets.DateInput(format="%m/%d/%Y"))
    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 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

我的观点:

class PersonCreate(CreateView):
    template_name = 'member/person_form.html'
    model = Person
    success_url = '/person/'
    form_class = MemberForm

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


class PersonUpdate(UpdateView):
    template_name = 'member/person_form.html'
    model = Person
    success_url = '/person/'
    form_class = MemberForm

我的会员在创建一个人时工作得很好。当用户不是唯一的,并且用户名和出生日期不是唯一的时,它还会在表单中给出验证错误。但是当我尝试更新保存的表单时,它会出错并说:"' MemberForm'对象没有属性'请求'"

如果我使用

 def get_form(self, form_class=None):
        form = super().get_form(form_class)
        form.request = self.request
        return form
在UpdateView中,它引发了我的自定义验证错误,如CreateForm。由于同一个人已经在数据库中。任何人都可以建议我如何修复Updateform以便正确更新我现有的数据。

1 个答案:

答案 0 :(得分:0)

工作代码是:

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

和观点:

class PersonUpdate(UpdateView):
    template_name = 'member/person_form.html'
    model = Person
    success_url = '/person/'
    form_class = MemberForm

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