2

I would like to do the following:

  1. I am displaying view1, with template1. There is a link to view2, rendering template2
  2. The user clicks the link
  3. When processing view2, an error occurs
  4. Now come the interesting part: I want to cancel rendering of view2, activate an error message, and display the previous view1/template1 (a kind of redirection, but not quite) But in view2 I do not know that I was coming from view1, and I also probably do not have the context that I had when view1 was rendered

How can I re-render view1, with the error message genarated in view2, so that the user the only new thing that sees is that error message? The full template1 should be rendered as before, including any form values that the user has entered.

This is similar to form validation, but would happen in the destination view instead of the form view.

Is this at all doable, or am I trying to do something completely impossible?

Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
blueFast
  • 41,341
  • 63
  • 198
  • 344

1 Answers1

0

There doesn't seem to be a way to "abort" a view, but you can get the behavior you want with the following pattern:

from django.contrib import messages
from django.shortcuts import redirect


def view1(request):
    if request.method == 'GET':
        initial_data = request.session.get('post_data', {})
        form = MyForm(initial=initial_data)
        ...


def view2(request):
    ...
    if error:
        request.session['post_data'] = request.POST
        messages.add_message(request, messages.ERROR, "Oops!")
        return redirect(request.META.get('HTTP_REFERER', '/'))

See this stack post for why preserving the POST data is painful and alternative ways of doing so.

Community
  • 1
  • 1
Ryne Everett
  • 6,427
  • 3
  • 37
  • 49