0

I know this might be a duplicate question, but the previous one was an older question and those questions uses a form instance which doesn't really help me.

How do I keep my form data after a failed validation? I have multiple dropdowns and input fields and I hate to see my users re-do and re-type everything when they fail validation in the backend. Let's say I have this very simple form:

HTML:

  <form class="" action="/register" method="post">
      <label for="">First Name</label>
      <input type="text" name="" value="">

      <label for="">Last Name</label>
      <input type="text" name="" value="">

      <label for="">Password</label>
      <input type="password" name="" value="">
    </form>

views.py:

def register(self):

    .....
    if errors:
        for err in errors
            messages.errors(request, err)
            return redirect('/')
    else:
        messages.success(request, "Welcome User!")
        return redirect('/dashboard')

Most examples that I came across were using the form instance which uses form.save() etc. I opted out on that one. Is there a way to auto-populate my form with the data that the user submitted if they were to fail validation? Thanks!

Marvin
  • 213
  • 1
  • 3
  • 9

1 Answers1

2

Django form classes are the way to go. Form validation and rendering are the tasks they were build for. I would strongly recommend using them, because they also take care of security aspects, when it comes to passing user input back to the browser (all input from user land is evil!).

If you really need to achieve this without form classes, you need to add the form values to your rendering context manually - this allows you to use them in your template.

The main problem with your approach is, that you want to redirect in case of validation error. A redirect is a response to the browser that tells: I have nothing for you, please go to this location. Usually the browser does not post the data send in the first request also to the second one (which is generally a good behavior). You may work around that by answering with status code 307 instead of 302. Read e.g. Response.Redirect with POST instead of Get? for more information. Alternatively you may encode your form data into the target location using get parameters.

Again: You should have a very good reason to not just use the django approach of one view that acts on GET and POST different and handles the form properly using the form instance.

dahrens
  • 3,879
  • 1
  • 20
  • 38