Send template data to database

Asked

Viewed 37 times

2

I am facing a problem that in Django, in which my form cannot be validated, therefore, does not enter the data in the database. I want the user to have the option of adding a teacher. The structure of the form is ok, but it’s as if the request didn’t even get done. I’ve tried it in many ways and none of it has served. Follow the code below.

File views.py:

def adiciona_professor(request):
    form = AdicionaProfessor()

    if request.method == 'POST':
        form = AdicionaProfessor(request.POST)

        if form.is_valid():
            nome = form.cleaned_data['nomecompleto_professor']
            email = form.cleaned_data['email_professor']
            cpf = form.cleaned_data['cpf']
            salvando = Professor(nomecompleto_professor=nome, email_professor=email, cpf=cpf)
            salvando.save()

    return render(request, 'evento_detalhe.html', locals())

Forms.py file:

class AdicionaProfessor(forms.ModelForm):

   class Meta:
       model = Professor
       fields = ('nomecompleto_professor', 'email_professor', 'cpf', )

template:

<div class="card">
                <div class="card-header" style="background: linear-gradient(90deg,#9cd116, #0AF6AE); font-weight: 100;">
                    <button class="btn btn-link" data-target="#collapse" data-toggle="collapse" style="color: #0b2e13; font-size: 1.2rem">
                       Adicionar professor
                    </button>
                </div>


                <!--
                  * No bloco abaixo, constam as informações dos cards
                -->
                <div class="container">
                    <div class="collapse" id="collapse">
                    <div class="card-body">
                        <form action="" method="POST">
                            {% csrf_token %}
                            {{ form.as_p }}
                            <div class="form-group">
                                <label for="exampleInputName1">Nome Completo</label>
                                <input type="text" class="form-control" id="exampleInputName1">{{formulario}}
                            </div>

                            <div class="form-group">
                                <label for="exampleInputEmail1">Endereço de email</label>
                                <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Seu email" {{email}}
                            </div>

                             <div class="form-group">
                                <label for="exampleInputCPF">CPF</label>
                                <input type="text" class="form-control" id="exampleInputCPF" aria-describedby="emailHelp"{{cpf}}>
                            </div>

                            <input type="submit" class="btn btn-default" value="Cadastrar">
                        </form>
                    </div>
                    </div>
                </div>
            </div>

I left a print('Chegou') to see if the forms would even arrive at the form.is_valid(), but it wasn’t enough.

I thank you for your attention!!

3 answers

3


I would make the view a little different. I believe the problem is there.

def adiciona_professor(request):
    if request.method == 'POST':
        form = AdicionaProfessor(request.POST)

        if form.is_valid():
            professor = form.save(commit=False)
            professor.nomecompleto_professor = form.cleaned_data['nomecompleto_professor']
            professor.email_professor = form.cleaned_data['email_professor']
            professor.cpf = form.cleaned_data['cpf']
            professor.save()
    else:
        form = AdicionaProfessor()

    return render(request, 'evento_detalhe.html', locals())
  • I kept thinking about it... will calling twice the form can cause conflict? taking the first line seems a suitable way

  • I tried your code, exactly as it is there. Nothing happened

  • 1

    Paulo, in fact, the problem was in the view. Colleague Carlos, below, asked a question about the situation of urls.py and admin.py. I didn’t modify them, but added a new view. It turns out that the form was already inside a previously made view, so the "add_teacher" should not exist. The code was put in the correct view and, anyway, it worked! Thank you very much!

2

if request.method == 'POST':
        form = AdicionaProfessor(request.POST)

You say your method apparently doesn’t even go through form.is_valid() most probably because the method that the view receive is not a string POST and as there is no E-is, nothing is done.

at first, for you to understand what happens put something like this:

print(request.method)
if request.method == 'POST':
    form = AdicionaProfessor(request.POST)
    ...
else
    print(f'o trecho {request.method} está sendo executado no else'}

if you can see in the console the prints means that you are not actually going through the first conditional, then a solution is:

print(request.method)
if str(request.method) == 'POST':
    form = AdicionaProfessor(request.POST)
    ... # todo o resto do código aqui
else
    print(f'o {request.method} está sendo executado no else'}

turns the request into a string that probably the code will pass in the snippet

  • So, Carlos, he didn’t execute anything. :/

  • Eita... as is the urls.py and admin.py?

  • I have not made any modifications to them. User adds teacher by bootstrap card. No screen is opened for form.

  • I did it. Your question of how the.py urls and admin.py were Eureka! for the hahaha answer. Thank you so much!

  • hahahahahahahahahaha... beodeos hahaha ok... if it’s working, it’s fine

0

Function based views

  def adiciona_professor(request):
        form = AdicionaProfessor(request.POST or None) #post ou None
        if str(request.method) == 'POST': # comparando com uma string
            if form.is_valid():   # verifica se esta okay
                nome = form.cleaned_data['nomecompleto_professor']
                email = form.cleaned_data['email_professor']
                cpf = form.cleaned_data['cpf']
               #salvar
                messages.success(request,"tarefa concluida!")
                form = ContatoForms()
            else:
                messages.error(request,"Erro!")
    
        context ={"form":form}
        return render(request, "evento_detalhe.html", context)

class Based views, simplifies much more than function

Browser other questions tagged

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