Keep data of fields after submit a form with an error on django

Question:

After I submit a form with an error with django, all fields of the form are cleaned. I want to keep the information on the fields, because it will help the users when they are submiting data.

This is my views.py of the aplication:

def new(request):
    context = {}
    if request.method == 'POST':
        form = NewSubject(request.POST)
        if form.is_valid():
            context['is_valid'] = True
            form.save()
            form = NewSubject()
        else:
            context['is_valid'] = False
    else:
        form = NewSubject()

    context['form'] = form
    return render(request, 'subjects/new.html', context)
Asked By: Joao Lucas

||

Answers:

I suggest you to use ajax .Because in that we can write different cases to handle if the submission is successful or not. if successful input.val(”) else
display error and not clean input field .

$('#post-form').on('submit', function(event){
event.preventDefault();
console.log("form submitted!")  // sanity check
create_post();)};   function create_post() {
console.log("create post is working!")
$.ajax({
    url : "/lrequestConfirmed/", // the endpoint
    type : "POST", // http method
    data : {
      datef: $('#datepicker').val(),
      type: $('#type').val(),
      reason: $('#reason').val()

    }, // data sent with the post request

    // handle a successful response
    success : function(json) {
        $('#datepicker').val(''); // remove the value from the input
        $('#reason').val(''); 
        $('#results').html("<div class='alert alert-success alert-dismissable'><a href='#'' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Success!</strong> Your request has been recored</div>");
        console.log(json); // log the returned json to the console
        console.log("success"); // another sanity check
    },

    // handle a non-successful response
    error : function(xhr,errmsg,err) {
        $('#results').html("<div class='alert alert-danger alert-dismissable'><a href='#'' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Oops!</strong> Something went wrong</div>"); // add the error to the dom
        console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
    }
});
Answered By: GauthamGAjith

Like Bear Brown said, the data keep on the fields after an error, but how I wasn’t using the pure forms from Django, I need to do some adjustments.
I created a hidden div with the origial Django forms and passed the data for my fields using JavaScript.
This is an example how I proceed:

The original Django forms has the id based on the field name on forms. So, if you define the name of the field on forms.py like “name”, the id of the field will be “id_name”:

function error(){ document.getElementById('name').value = document.getElementById('id_name').value;}

This is how the fields on form are called. After it’s render, it will contains the data of the form field and have an id, so I get the element by id (“id_name”) and tranfer the information for my personalizated field.

<div style="display: none;">
   {{ form.name }}
</div>

This is the field with my stylization where the user will edit the data and make his own modifications.

<input id="name" class="form-control" type="text" maxlength="100" name="name" placeholder="Ex.: Metemática" onchange="slugDefine()" onkeyup="slugDefine()" /><br>

Thank you for your help!

Answered By: Joao Lucas

If you do not want to use Javascript, you can use the value keyword in your HTML template. But ensure you have a return statement in your else statement when the form is not valid.

def new(request):
    context = {}
    if request.method == 'POST':
        form = NewSubject(request.POST)
        if form.is_valid():
            context['is_valid'] = True
            form.save()
            form = NewSubject()
        else:
            context['is_valid'] = False
            return render(request, 'subjects/new.html', context)
    else:
        form = NewSubject()

    context['form'] = form
    return render(request, 'subjects/new.html', context)

Then, in your HTML template, you can add the value="{{ form.billing_email.value }}" to your div tag. For example,

<div class="">
      <label for="billing_email" class="">
             Billing contact email:
      </label>
       <input
          type="email"
           class=""
           name="billing_email"
           id="billing_email"
           placeholder="Text"
           value="{{ form.billing_email.value }}"      
            />
           {% for error in form.billing_email.errors %}
                <div class="">{{ error }}</div>
            {% endfor %}
     </div>
Answered By: Toluwalemi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.