Django - No se envía la información de mi formulario a la base de datos

 
Vista:
Imágen de perfil de Natalia
Val: 5
Ha mantenido su posición en Django (en relación al último mes)
Gráfica de Django

No se envía la información de mi formulario a la base de datos

Publicado por Natalia (3 intervenciones) el 29/08/2021 14:32:59
Hola, he creado un formulario para crear un beneficiario en la base de datos, el formulario valida todas las opciones, y no deja enviar si no esta completo, cuando le doy guardar, me redirecciona a la pagina de guardado exitoso, pero cuando reviso no ha creado el beneficiario en la base de datos, y no entiendo porque, tambien trato de que me muestre los errores con form.errors y tampoco me muestra nada.

Este es mi modelo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Beneficiario(models.Model):
    benef_id = models.CharField(primary_key=True, max_length=20)
    benef_nombres = models.CharField(max_length=200)
    benef_apellidos = models.CharField(max_length=200)
    benef_nombrepref = models.CharField(max_length=200)
    benef_sexo = models.ForeignKey('Sexo', models.DO_NOTHING, db_column='benef_sexo')
    benef_fechanac = models.DateField()
    benef_grupoeta = models.ForeignKey('Grupoetareo', models.DO_NOTHING, db_column='benef_grupoeta')
    benef_huerfano = models.BooleanField()
    benef_nav = models.BooleanField()
    benef_barrio = models.CharField(max_length=200, blank=True, null=True)
    benef_direccion = models.CharField(max_length=200)
    benef_telefono = models.BigIntegerField(blank=True, null=True)
    benef_correo = models.CharField(max_length=120)
    benef_ciudad = models.ForeignKey('Ciudades', models.DO_NOTHING, db_column='benef_ciudad')
    benef_departamento = models.ForeignKey('Departamento', models.DO_NOTHING, db_column='benef_departamento')
    benef_eduformal = models.ForeignKey('Educacionformal', models.DO_NOTHING, db_column='benef_eduformal')
    benef_rendiaca = models.ForeignKey('Rendimientoacademico', models.DO_NOTHING, db_column='benef_rendiaca')
    benef_religion = models.ForeignKey('Religion', models.DO_NOTHING, db_column='benef_religion')
    benef_activcrist = models.ForeignKey('Actividadescristianas', models.DO_NOTHING, db_column='benef_activcrist')
    benef_img = models.ImageField(upload_to='plantillas', default= 'null')
    benef_created = models.DateTimeField(auto_now_add=True)
    benef_updated = models.DateTimeField(auto_now_add=True)
    benef_hobbies = models.ManyToManyField('Hobbies')
    benef_materias = models.ManyToManyField('Materias')
    benef_deberes = models.ManyToManyField('Deberes')

Ahi tiene varias relaciones con otras tablas que sì estan creadas todas.

Este es mi formulario:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from django.forms import *
from plantillas.models import Beneficiario
#from betterforms.multiform import MultiModelForm
 
 
class formFichaReg(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for form in self.visible_fields():
           form.field.widget.attrs.update({'autocomplete': 'off'})
           #self.fields['benef_id'].widget.attrs.update({'autofocus': True})
           self.fields['benef_fechanac'].widget.attrs.update({'placeholder': 'formato aaaa/mm/dd'})
 
    class Meta:
        model = Beneficiario
        fields = '__all__'
        labels = {
            'benef_id' : 'identificacion',
            'benef_nombres' : 'Nombres',
            'benef_apellidos': 'Apellidos',
            'benef_nombrepref': 'Nombre Preferido',
            'benef_sexo': 'Sexo',
            'benef_fechanac': 'Fecha de Nacimiento',
            'benef_grupoeta': 'Grupo Etareo',
            'benef_huerfano' : 'Es Huerfano',
            'benef_nav': 'Es Niño Altamente Vulnerable',
            'benef_barrio': 'Barrio',
            'benef_direccion': 'Dirección',
            'benef_telefono': 'Teléfono',
            'benef_correo': 'Correo',
            'benef_ciudad': 'Ciudad',
            'benef_departamento': 'Departamento',
            'benef_eduformal': 'Educación Formal',
            'benef_rendiaca': 'Rendimiento Académico',
            'benef_religion' : 'Religión',
            'benef_activcrist': 'Actividades Cristianas',
            'benef_img': 'Foto',
            'benef_created' : 'Fecha de Creación',
            'benef_updated' : 'fecha de Actualización',
            'benef_hobbies' : 'Hobbies',
            'benef_materias' : 'Materias',
            'benef_deberes' : 'Deberes',
 
        }
        {
            'benef_fechanac': DateInput(
                #attrs = {
                   #'placeholder':'Ingrese un nombre',
               # }
 
            )
 
        }
        {
            'benef_huerfano': BooleanField(
                #attrs = {
                   #'placeholder':'Ingrese un nombre',
               # }
 
            )
 
        }
        {
            'benef_activcrist': SelectMultiple(
                #attrs = {
                   #'placeholder':'Ingrese un nombre',
               # }
 
            )
 
        }
        {
            'benef_correo': EmailField(
                #attrs = {
                   #'placeholder':'Ingrese un nombre',
               # }
 
            )
 
        }


Esta es mi vista:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from django.shortcuts import render
from django.urls.base import reverse_lazy
from django.views.generic import CreateView
from plantillas.forms import formFichaReg
from plantillas.models import Beneficiario
from django.http import HttpResponseRedirect
from django.views import View
from django.http import HttpRequest, HttpResponse
 
 
def plantillas(request):
    return render(request, 'plantillas/adminPlantillas.html')
 
 
def success(request):
    return render(request, 'plantillas/success.html')
 
class fichaSocReg(CreateView):
    model=Beneficiario
    form_class = formFichaReg
    template_name = 'plantillas/adminFicha.html'
 
    def post(self, request, ):
        form = self.form_class(request.POST)
        if form.is_valid():
        # <process form cleaned data>
            return HttpResponseRedirect(reverse_lazy('success') )


y mi template:



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
{% extends "axyProyectApp/baseaxy.html" %}
 
{% load static %}
 
 
{% block title %}
 
 
<title>Ficha Social de Registro</title>
 
{% endblock %}
 
{% block content %}
<!----Encabezado-->
<div class="row border">
  <!----Navegacion-->
 
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container-fluid">
      <h3 class="text-primary" href="#">AXY Software</h3>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link" aria-current="page" href="#"></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" aria-current="page" href="{% url 'PanelPrincipal' %}">Inicio</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" aria-current="page" href="{% url 'NuevoDocumento' %}">Nuevo Documento</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" aria-current="page" href="{% url 'Plantillas' %}">Plantillas</a>
          </li>
 
          <li class="nav-item  dropdown">
            <a class="nav-link active" href="#" role="button" aria-expanded="false">
              Ficha Social de Registro de Beneficiario
            </a>
 
 
          </li>
        </ul>
 
      </div>
    </div>
  </nav>
 
 
  <div class="d-flex justify-content-end">
    <a href="{% url 'Login' %}"><button type="button" class="btn-close btn-close-primary"
        aria-label="Close"></button></a>
  </div>
</div>
 
<div class="row ">
  <h3 class="text-center fw-bold">Información del Beneficiario</h6>
    <p class="text-end">Programa CDSP-Center Based</p>
    <form action="{% url 'success' %}" method="POST">
      {% csrf_token %}
      <div class="alert alert-primary alert-dismissible fade show" role="alert">
        <strong>Notificación: </strong> {{ form.errors}}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        <P></P>
    </div>
 
      <div class="row mb-3">
        <div class="form-check col-xs-12 col-md-4 mb-3">
          <label>
            Tipo de Información
          </label>
        </div>
        <div class="form-check col-xs-12 col-md-4 mb-3">
          <input class="form-check-input" type="radio" name="flexRadioDefault" id="rRegNuevo" checked>
          <label class="form-check-label" for="rRegNuevo">
            Registro Inicial
          </label>
        </div>
        <div class="form-check col-xs-12 col-md-4 mb-3">
          <input class="form-check-input" type="radio" name="flexRadioDefault" id="rActuli">
          <label class="form-check-label" for="rActuali">
            Actualización
          </label>
        </div>
        {% for field in form.visible_fields %}
        <div class="row">
 
            <label for="{{ field.name }}" class="form-label">{{ field.label }}</label>
            {{ field }}
 
        </div>
        {% endfor %}
 
      </div>
 
</div>
 
 
 
<div class="row mb-3 justify-content-center">
 
 
  <div class="col-md-6 col-lg-6 mb-3">
    <div class="row  mx-5 d-flex justify-content-center">
      <button class="btn btn-primary" type="submit">Guardar</button>
    </div>
  </div>
 
 
</div>
 
 
</form>
</div>
 
{% endblock %}



Les agradezco si alguien tiene una opinion de que puede estar pasando.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder