Created
March 29, 2021 20:30
-
-
Save zulu15/fefd9143bc3eea428932f7873e7bcefb to your computer and use it in GitHub Desktop.
form, formsets error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
definición del form y del formset: | |
''' | |
archivo forms.py | |
''' | |
class AutorForm(forms.ModelForm): | |
def clean_nombre(self): | |
return escape(self.cleaned_data.get('nombre')) | |
def clean_apellido(self): | |
return escape(self.cleaned_data.get('apellido')) | |
class Meta: | |
model = Autor | |
fields = ["nombre","apellido"] | |
labels = { | |
} | |
widgets = { | |
'nombre':forms.TextInput( | |
attrs = { | |
'id':'nombre', | |
'class':'form-control', | |
'placeholder':'Nombre del autor', | |
'list':'autores_nombre_list' | |
} | |
), | |
'apellido':forms.TextInput( | |
attrs = { | |
'id':'apellido', | |
'class':'form-control', | |
'placeholder':'Apellido del autor', | |
'list':'autores_apellido_list' | |
} | |
), | |
} | |
class LibroForm(forms.ModelForm): | |
def clean_titulo(self): | |
return escape(self.cleaned_data.get('titulo')) | |
def clean_descripcion(self): | |
return escape(self.cleaned_data.get('descripcion')) | |
def __init__(self, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
#self.fields["autor_id"].queryset = Autor.objects.filter(estado = True) | |
class Meta: | |
model = Libro | |
fields = ['titulo','imagen'] | |
labels = { | |
'titulo':'Ingrese el título del libro', | |
'autor_id':'Seleccione los autores del libro', | |
'fecha_publicacion':'Indique la fecha de publicación del libro' | |
} | |
widgets = { | |
'titulo':forms.TextInput( | |
attrs = { | |
'placeholder':'Ingrese el Título del libro', | |
'class':'form-control', | |
'id':'titulo', | |
'list':'titulos' | |
} | |
), | |
'autor_id':forms.SelectMultiple( | |
attrs = { | |
'class':'form-control', | |
'id':'autor_id' | |
} | |
), | |
'fecha_publicacion':forms.SelectDateWidget( | |
attrs = { | |
'class':'form-control', | |
'id':'fecha_publicacion' | |
} | |
), | |
'descripcion': forms.Textarea(attrs={ | |
'class':'form-control' | |
}), | |
'cantidad': forms.NumberInput(attrs={ | |
'class':'form-control' | |
}) | |
} | |
''' | |
fin del archivo forms.py | |
''' | |
''' | |
Archivo views.py | |
''' | |
class CrearLibro(LoginRequiredMixin, CheckRecaptchaMixin, CreateView): | |
model = Libro | |
template_name = 'libro/libro/crear_libro.html' | |
formset = formset_factory(AutorForm, extra = 1) | |
form_class = LibroForm | |
def post(self, request, *args, **kargs): | |
if request.is_ajax(): | |
if request.captcha_invalid: | |
mensaje = "Por favor complete el captcha!" | |
error = {"captcha": "El captcha expiró o es inválido"} | |
status_code = 400 | |
else: | |
forms = self.formset(request.POST, request.FILES, prefix = "autores") | |
print("Mostrando contenido de forms") | |
for f in forms: | |
print(f) | |
print(f"{f.is_valid()}") | |
#Error is_valid siempre es true cuando el form viene vacío | |
form = self.form_class(data = request.POST, files = request.FILES) | |
if form.is_valid(): | |
form.save() | |
mensaje = f"El {self.model.__name__} se ha registrado correctamente!" | |
error = "No hay error!" | |
status_code = 201 | |
else: | |
mensaje = f"El {self.model.__name__} no se ha registrado correctamente" | |
error = form.errors | |
status_code = 400 | |
response = JsonResponse({"mensaje": mensaje, "error": error}) | |
response.status_code = status_code | |
return response | |
return redirect("libro:inicio_libro") | |
def get(self, request, *args, **kargs): | |
libros = self.model.objects.all() | |
f = self.formset(prefix = "autores") | |
autores = Autor.objects.all() | |
return render(request, self.template_name, {"formset": f, "form":self.form_class(prefix = "libro"),"libros":libros, "autores":autores}) | |
''' | |
Fin de views.py | |
''' | |
''' | |
Archivo models.py | |
''' | |
class Autor(models.Model): | |
id = models.AutoField(primary_key = True) | |
nombre = models.CharField(max_length = 200, blank = False, null = False) | |
apellido = models.CharField(max_length = 220, blank = False, null = False) | |
nacionalidad = models.CharField(max_length = 100, blank = False, null = False) | |
descripcion = models.TextField("Descripción", blank = True, null = True) | |
fecha_creacion = models.DateField("Fecha de creación", auto_now = True, auto_now_add = False) | |
estado = models.BooleanField("Estado", default = True) | |
class Meta: | |
verbose_name = "Autor" | |
verbose_name_plural = "Autores" | |
ordering = ["nombre"] | |
def __str__(self): | |
return self.nombre + " " + self.apellido | |
def natural_key(self): | |
return f"{self.nombre} {self.apellido}" | |
Definición del template | |
<form id="form_creacion" action="{% url 'libro:crear_libro' %}" method="POST"> | |
{% csrf_token %} | |
<div class="modal-body"> | |
<div id="errores"> | |
</div> | |
<p class="font-weight-bold">1) Primero complete los datos del libro.</p> | |
{{ form.as_p }} | |
<p class="font-weight-bold">2) Segundo complete los datos del(os) autor(es) del libro.</p> | |
<div id="autores_form"> | |
<p><strong>Autor 1:</strong></p> | |
{{ formset.management_form }} | |
{% for f in formset %} | |
{{ f.as_p }} | |
{% endfor %} | |
<hr> | |
</div> | |
<button type="button" class="btn btn-primary" onclick="agregar_autor(event);">Agregar autor extra</button> | |
<!-- DATA LIST AUTOCOMPLETADO --> | |
<datalist id="autores_nombre_list" > | |
{% for autor in autores %} | |
<option value="{{ autor.nombre }}"> | |
{% endfor %} | |
</datalist> | |
<datalist id="autores_apellido_list" > | |
{% for autor in autores %} | |
<option value="{{ autor.apellido }}"> | |
{% endfor %} | |
</datalist> | |
<datalist id="titulos" > | |
{% for libro in libros %} | |
<option value="{{ libro }}"> | |
{% endfor %} | |
</datalist> | |
<p class="font-weight-bold">3) Haga click en "no soy un robot" y complete el desafio.</p> | |
<div class="g-recaptcha" id="captcha" data-sitekey="6LdJ_oMaAAAAAGBjB1kN8-kTnAuAU1Ft1q2ukzbk"></div> | |
</div> | |
<div class="modal-footer"> | |
<button id="boton_creacion" class="btn btn-primary" type="button" onclick="registrar()">Confirmar</button> | |
</div> | |
</form> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment