How to clear the fields of a form in Django

Asked

Viewed 441 times

0

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

inserir a descrição da imagem aqui

  • If it’s a form, try it with autocomplete="off" on the tag form.

1 answer

0


I believe that after the POST is departing from his index and redirecting to itself index (type one single page application).

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

Try creating 2 form instances.

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:

https://repl.it/@natorsc/Django

  • Thanks, it worked out!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.