'Override dispatch() method in PasswordResetConfirmView

I have written a class that inherits from PasswordResetConfirmView

PasswordResetConfirmView can be found here: https://github.com/django/django/blob/7f4fc5cbd4c26e137a1abdd9bd603804ddc0e769/django/contrib/auth/views.py#L260

For what it's worth here is the part of the class that I have written (nothing ground breaking I know!):

    class PwdResetConfirm(PasswordResetConfirmView):
        template_name = 'account/password_reset_confirm.html'
        success_url = reverse_lazy('two_factor:login')
        form_class = PwdChangeForm

What I want to do is change the behaviour of PasswordResetConfirmView dispatch() method so that a message is created if a password reset is unsuccessful, so the lines in PasswordResetConfirmView:

    # Display the "Password reset unsuccessful" page.
    return self.render_to_response(self.get_context_data())

would effectively become:

    messages.success(self.request, _(mark_safe(
          'Your password change link appears to be invalid.')))

    # Display the "Password reset unsuccessful" page.
    return self.render_to_response(self.get_context_data())

I am new to overriding classes and as such,I am not even sure where to start.

In summary, my question is:

How can I add the message to PasswordResetConfirmView class's dispatch() method without overriding the entire method?

UPDATE I have found what I believe to be the best solution to my problem.

Thank you @Michael B for his post

Background: If the password reset link is found to be invalid PasswordResetConfirmView's dispatch() method calls the self.get_context_data() method and then renders the response.

Solution: By adding the message within get_context_data() and then updating the context dict using get_messages(self.request) method.

Solution example

from django.contrib.messages import get_messages

class PwdResetConfirm(PasswordResetConfirmView):
    template_name = 'account/password_reset_confirm.html'
    success_url = reverse_lazy('two_factor:login')
    form_class = PwdChangeForm

    def get_context_data(self, **kwargs):
        context = super(PwdResetConfirm, self).get_context_data(**kwargs)

        if not context['validlink']:
            messages.success(self.request,
                         _('Your password change link appears to be invalid.'))
            context.update({'messages': get_messages(self.request)})

        return context


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source