Home > Net >  Django - overload post on UpdateView so it auto completes some fields
Django - overload post on UpdateView so it auto completes some fields

Time:02-05

So I have this view:

class ProfileView(generic.UpdateView):
    model = User
    fields = [....]
    template_name_suffix = '_update_form'
    success_url = reverse_lazy('home')

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.object.is_active = False
        return super().post(request, *args, **kwargs)

when the user saves his data on update, I want some fields to be completed automatically, such as is_active = False.

I used the approach above but my inserted fields aren't changed.

Why and how can I get the desired result?

Thanks.

CodePudding user response:

There will be two objects here: the one wrapped in the form, and the one you use in the .post method, and you save the one in the form.

You can override the .form_valid(…) method [Django-doc]:

class ProfileView(generic.UpdateView):
    model = User
    fields =  # …
    template_name_suffix = '_update_form'
    success_url = reverse_lazy('home')

    def form_valid(self, form):
        form.instance.is_active = False
        return super().form_valid(form)
  • Related