Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class based view extending UpdateView not saving form correctly

Im trying to save a form using UpdateView in Django 1.3 and seemed to have run into a problem. When I am saving the form, it POST's to the current URL and the success url is the same url.

When saving the form, the data seems to be changed because all the fields on the page are updated, but when I refresh, everything seems to revert.

The form is a Model Form and here is my view:

class UserProfileView(UpdateView):
    context_object_name = 'profile'

    def get_template_names(self):
        return ['webapp/user_profile.html']

    def get_queryset(self):
        pk = self.kwargs.get('pk', None)

        if pk is not None:
            user = User.objects.get(pk=pk)
        else:
            raise AttributeError(u"Could not locate user with pk %s"
                             % pk)

        if user.contributor_profile.all():
            queryset = Contributor.objects.filter(user__pk=pk)
        else:
            queryset = Member.objects.filter(user__pk=pk)

        return queryset

    def get_object(self, queryset=None):
        if queryset is None:
            queryset = self.get_queryset()

        return queryset.get()

I dont see what could be going wrong, seeing as Django saves the form through the UpdateView class and the Mixin's it extends. Has anyone run into this problem before?

like image 699
Omar Estrella Avatar asked May 05 '11 14:05

Omar Estrella


1 Answers

Figured out the solution. The problem was happening because there was an error in the form that wasnt being reported. This seems to occur with hidden fields that need to be set in some way in order for the form to be valid.

The solution is pretty simple. You just need to override the post function and account for any hidden fields:

def post(self, request, *args, **kwargs):
    pk = self.kwargs.get('pk', None)

    if pk is not None:
        user = User.objects.get(pk=pk)
    else:
        raise AttributeError(u"Could not locate user with pk %s"
                             % pk)

    if user.contributor_profile.all():
        contributor = Contributor.objects.get(user=user)
        form = ContributorForm(request.POST, instance=contributor)
    else:
        member = Member.objects.get(user=user)
        form = MemberForm(request.POST, instance=member)

    if form.is_valid():
        self.object = form.save()
        return HttpResponseRedirect(self.get_success_url())
    else:
        return self.render_to_response(self.get_context_data(form=form))
like image 188
Omar Estrella Avatar answered Oct 14 '22 21:10

Omar Estrella