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!!
I kept thinking about it... will calling twice the form can cause conflict? taking the first line seems a suitable way
– Carlos Cortez
I tried your code, exactly as it is there. Nothing happened
– BeatrizGomes
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!
– BeatrizGomes