How to update Forms in Django

Asked

Viewed 141 times

1

Hello, everybody. Here’s the thing: I have two presses that integrate with a model in Django, being them:

Forms.py

from datetime import datetime
from django import forms
from .models import CadastroModel

class CadastroForm(forms.Form):
    nome = forms.CharField(label="Nome", max_length=200)


class AddPontoForm(forms.Form):    
    tipos = [(0, 'Selecione'), (1, 'Entrada'), (2, 'Intervalo'), (3, 'Retorno'), (4, 'Saida'),]
    nomes_cad = CadastroModel.objects.all()
    nomes = []
    i = 0
    for n in nomes_cad:
        nomes.append((i, n.nome))
        i += 1
    nome = forms.ChoiceField(label="Nome", choices=nomes)
    dia = forms.DateField(label="Dia", initial=datetime.today())
    tipo = forms.ChoiceField(label="Marcacao", choices=tipos)
    hora = forms.CharField(label="Hora", max_length=200)

py.models

from django.db import models

class CadastroModel(models.Model):
    nome = models.CharField(max_length=200)

    def __str___(self):
        return self.nome

py views.

def cadastro(request):
    form = CadastroForm(request.POST or None)
    if str(request.method) == "POST":
        if form.is_valid():
            nome = form.cleaned_data['nome']
            novo_func = CadastroModel(nome=nome)
            novo_func.save()
            messages.success(request, "Funcionario(a) cadastrado(a) com sucesso!")
        else:
            messages.error(request, "Falha no cadastro!")

That is, I use the data entered in the Cadastroform to enter names in the database. The problem is that in the Addpontoform form, in the field nome, is performed a search in db that should return the registered names. However, when I enter the names in Cadastroform, they are saved correctly, but do not update the list of names in the Addpontoform form, even if I reload the page, close and open it again. I need to stop the server, and start it again so that the listing appears updated.

How can I make it so that once one adds a new name to the database it already appears in the list of names in the other form?

  • Hi, aren’t you missing one of your models? Your view.py function is complete?

  • Yes, I have other form/model that has the same fields (name, date, type and time) and another view that renders this other form and inserts this data into db. But related to my question, it is only the 'name' field that does not update in the Addpontoform form when I enter a new employee. It’s like the nomes_cad = CadastroModel.objects.all() stopped working properly and does not return the complete search in the database with the new records in the model Cadastromodel.

1 answer

1


Nathan, when you load the data this way

class AddPontoForm(forms.Form):    
    tipos = [(0, 'Selecione'), (1, 'Entrada'), (2, 'Intervalo'), (3, 'Retorno'), (4, 'Saida'),]
    nomes_cad = CadastroModel.objects.all()
    nomes = []
    i = 0
    for n in nomes_cad:
        nomes.append((i, n.nome))
        i += 1
    nome = forms.ChoiceField(label="Nome", choices=nomes)

You’re actually loading the data the moment Django starts. Therefore, you will not reload the data for each request that is made. If you want to do a test, add a new CadastroModel and restart the Django server. The data will appear in the list.

But there’s a guy named Django in Django’s documentation Modelchoicefield who is responsible for loading the options according to a queryset. which I believe is what you are looking for.

class AddPontoForm(forms.Form):    
    tipos = [(0, 'Selecione'), (1, 'Entrada'), (2, 'Intervalo'), (3, 'Retorno'), (4, 'Saida'),]
    nome = forms.ModelChoiceField(label="Nome", queryset=CadastroModel.objects.all())
    dia = forms.DateField(label="Dia", initial=datetime.today())
    tipo = forms.ChoiceField(label="Marcacao", choices=tipos)
    hora = forms.CharField(label="Hora", max_length=200)

Browser other questions tagged

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