How to clear fields from a form in Django

0

I'm studying Django and I'm following a course, which is setting up a Spending Control. However I am not 100% faithful to the course, I am making some modifications. My problem is this, when I register a transaction, the form fields are not cleaned up when it returns to the homepage, how do I fix this?

    
asked by anonymous 04.07.2018 / 02:38

1 answer

0

I believe that after POST is starting from your index and redirecting to index itself (type a single page application ).

If it is you should be sending the form that received request.POST ( form = NomeDoFurmulárioForm(request.POST) ), so the modal is opening with the completed form.

Try to create 2 instances of the form.

Ex :

from django.shortcuts import render
from .forms import GastosForm
from .models import Gastos


def home(request):
    # Formulário vazio.
    form = GastosForm()

    # Valores do banco para a tabela.
    table = Gastos.objects.all()

    # Verificando o método que foi enviado.
    if request.method == 'POST':

        # Formulário com os valores do modal.
        formPOST = GastosForm(request.POST)

        # Se o formulário é valido.
        if formPOST.is_valid():

            # Salvando os dados.
            formPOST.save()

            # Retornando o formulário vazio.
            return render(request, 'main/index.html', {'form': form, 'table': table})

        # Se houver algum erro (formulário não válido).
        else:

            # Retornando **formPOST** que é o formulário preenchido, juntamente com o erro.
            return render(request, 'main/index.html', {'form': formPOST, 'table': table})

    # Se o método é GET.
    else:
        # Retornado o formulário vazio.
        return render(request, 'main/index.html', {'form': form, 'table': table})

Ex :

link

    
04.07.2018 / 18:30