django - Update form not work after using custom clean method -
my model form:
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 submitted data") elif person.objects.filter(name=name, birth_date=birth_date).exists(): self.add_error('name', "person name , birth date 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
my views:
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
my memberform worked fine when create person. give validation errors in form when user not unique , user name , birth date combinedly not unique. when tried update saved form gives error , say: "'memberform' object has no attribute 'request'"
if use
def get_form(self, form_class=none): form = super().get_form(form_class) form.request = self.request return form
in updateview raises custom validation errors createform. since same person in database. suggest me way how fix updateform correctly update existing data.
the working code is:
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 submitted data") elif person.objects.filter(name=name, birth_date=birth_date).exclude(id=self.instance.id).exists(): self.add_error('name', "person name , birth date exists.") else: if person.objects.filter(user=user).exists(): self.add_error('name', "you submitted data") elif person.objects.filter(name=name, birth_date=birth_date).exists(): self.add_error('name', "person name , birth date exists.") return self.cleaned_data
and in views:
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
Comments
Post a Comment