Search code examples
pythondjangoforms

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


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)

Solution

  • 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!