I’m having a problem with Django-views, he’s not saving my form

Asked

Viewed 805 times

0

This is my views:


from django.shortcuts import render
from meusite.forms import CandidatoForm
from meusite.models import Candidato


def index(request):
    return render(request, 'index.html') #renderizando (interpretando e colocando na pagina html)

def cadastro(request):
    return render(request, 'cadastro.html')

def sobre(request):
    return render(request, 'sobre.html')

def cadastrados(request):
    cadastrados = Candidato.objects.all()
    contexto = {
        'cadastrados' : cadastrados,
    }
    return render(request, 'cadastrados.html', contexto)

def fazer_cadastro(request):
    #ENTRAR PELA PRIMEIRA VEZ NO SITE USA METODO REQUEST.GET
    #ENTRA PELO CLICK ENVIANDO O FORMULARIO USA O METODO REQUEST.POST)  
    candidatos = Candidato.objects.all()
    formulario = CandidatoForm(request.POST or None)
    msg = ''

    if formulario.is_valid():
        formulario.save()
        formulario = CandidatoForm() #depois de enviar, apaga
        msg = 'Cadastro realizado com sucesso'

    contexto = {
        'form' : formulario,
        'msg' : msg
    }

    #CONTEXTO: MANDA COISAS DO PYTHON PRO HTML (ACESSA FORMULARIO DO BACKEND PRO FRONTEND)
    return render(request, 'cadastro.html', contexto)

Here are my models

class Candidato(models.Model):

    genero_feminino = 'f'
    genero_masculino = 'm'
    genero_outro = 'o'

    genero_opcoes = [
        (genero_feminino, 'Feminino'),
        (genero_masculino, 'Masculino'),
        (genero_outro, 'Outro'),
    ]

    nome = models.CharField(max_length=100, default=" ")
    idade = models.IntegerField()
    genero = models.CharField(max_length=11, choices=genero_opcoes, default=" ")
    data_nascimento = models.DateField()
    nacionalidade = models.CharField(max_length=50, default=" ")
    ja_trabalha = models.BooleanField(default=True)
    pretencao_salarial = models.DecimalField(decimal_places=2, max_digits=1000, default=0)
    perfil = models.TextField(default=" ")
    foto = models.ImageField(upload_to='', null=True)

    def __str__ (self):
        return self.nome

For some reason I am not able to save who fills the form or display messages like "The form has been filled out successfully!" Can anyone help me solve this error?

3 answers

0

I managed to solve my problem as follows:

VIEWS:

def cadastro(request):
if request.method == "POST":
  form = CandidatoForm(request.POST)
  if form.is_valid():
        candidado = form.save()
        msg = "Cadastro realizado com sucesso"
        return({'msg':msg})
else:
    form = CandidatoForm()       
return render(request, 'cadastro.html', {'form':form})

0

how is calling the form in the template cadastro.html? As you passed a message to context, you need to call it in the template {{ msg }}. By the tests I did here it may be that the form has invalid data, check the model attributes: data_nascimento and the foto.

{{ msg }}
<form action="." method="post">{% csrf_token %}
    {{ form }}
    <button type="submit" name="button">Enviar</button>
</form>

I hope I’ve helped a little, update us on your progress. This site has a lot of cool content. It might be more interesting to use the Django message framework. https://simpleisbetterthancomplex.com/tips/2016/09/06/django-tip-14-messages-framework.html

  • Thank you so much for your help, I will take these fields and see if saved.

  • Unfortunately it still hasn’t worked, even if I take these fields out of code :C

  • Could you put the error that is returning? How are you testing?

0

Good morning Amanda,

All right?

Amanda, I rewrote the code a little bit, I hope it helps:

#forms.py
from .models import Candidato
from django import forms


class CandidatoForm(forms.ModelForm):
    class Meta:
        model = Candidato
        fields = '__all__'


#views.py
from django.views import generic
from django.contrib.messages.views import SuccessMessageMixin
from django.urls import reverse_lazy
from .models import Candidato
from .forms import CandidatoForm


class CadastroCreateView(SuccessMessageMixin, generic.CreateView):

    form_class = CandidatoForm
    model = Candidato
    success_message = 'Cadastro realizado com sucesso'
    success_url = reverse_lazy('suaurl')

    def candidatos(self):
        return Candidato.objects.all()

#seu template html

#para exibir a lista de candidatos obtida no metodo def candidatos(), basta fazer o seguinte:
{% for c in view.candidatos %}
    {{ c }}
{% endfor %}

#aqui será exibido a mensagem de sucesso que é passada para o template através do 
success_message na view
{% for m in messages %}
    {{ m }}
{% endfor %}

<form action="" method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Salvar</button>
</form>

Amanda, if possible, runs a Manage.py makemigrations and Manage.py migrates again, if you have an error in your view, Forms, or model, will appear during the process.

  • Thank you so much for the help, I got my form to work! :D

Browser other questions tagged

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