django update view and passing context

3.4k views Asked by At

I have a update view:

class GeneralUserUpdateView(UpdateView):

    model = GeneralUser
    form_class = GeneralUserChangeForm
    template_name = "general_user_change.html"

    def dispatch(self, *args, **kwargs):
        return super(GeneralUserUpdateView, self).dispatch(*args, **kwargs)

    def post(self, request, pk, username):

        self.pk = pk
        self.username = username
        self.gnu = GeneralUser.objects.get(pk=self.pk)
        #form = self.form_class(request.POST, request.FILES)
        return super(GeneralUserUpdateView, self).post(request, pk)

    def form_valid(self, form, *args, **kwargs):
        self.gnu.username = form.cleaned_data['username']
        self.gnu.email = form.cleaned_data['email']
        self.gnu.first_name = form.cleaned_data['first_name']
        self.gnu.last_name = form.cleaned_data['last_name']
        self.gnu.address = form.cleaned_data['address']
        self.gnu.save()

        return redirect("user_profile", self.pk, self.username)

Here in this view I want to pass a context like:

context['picture'] = GeneralUser.objects.get(pk=self.pk)

I did trying get_context_data but I cant access pk in there.. Am I doing the update right?? How can I pass that context in there??

1

There are 1 answers

1
Daniel Roseman On BEST ANSWER

You shouldn't be overriding post at all. All of that logic should happen in get_context_data.

In fact, none of your overrides are needed. Everything that you do in form_valid will be done already by the standard form save. And overriding dispatch just to call the superclass is pointless.

Your view should look like this only, with no overridden methods at all:

class GeneralUserUpdateView(UpdateView):
    model = GeneralUser
    form_class = GeneralUserChangeForm
    template_name = "general_user_change.html"
    context_object_name = 'picture'

(although it seems a little odd that you want to refer to an instance of GeneralUser as "picture").

Edit to redirect to a specific URL, you can define get_success_url:

    def get_success_url(self):
        return reverse("user_profile", self.kwargs['pk'], self.kwargs['username'])