Pre-validation using the CreateView form

1

I am using the generic views of Django to register / enter a product, the idea or the question is how I can evaluate previously said form sent to your view, my code to create is the following:

class CrearProducto(CreateView):

    model = Producto
    form_class = ProductoForm
    template_name = "administrador/crear_producto.html"
    success_url = "/productos/administrar_productos"

@receiver(post_save, sender=Producto)
def GrabarMovimientos(sender, instance, *args, **kwargs ):

    producto_actual = Producto.objects.get(nombre=instance.nombre)

    movimiento = Movimientos(
        tipo = 1,
        proveedor = instance.proveedor,
        producto = producto_actual,
        bodega = instance.bodega,
        vunitario_promedio = float(instance.precio),
        #responsable = usuario,
        vunitario_compra = float(instance.precio),
        cant_ingreso = instance.cantidad,
        tot_ingreso = float(instance.cantidad) * float(instance.precio),
        tot_saldo = float(instance.cantidad) * float(instance.precio),
        cant_saldo = instance.cantidad,
    )
    movimiento.save()

In the view CreateView I save the products which makes good once the data is recorded I make a callback to GrabarMovimientos this is responsible for recording a movement for the handling of Kardex, it also does it well, the question is how validate within CreateView that meets certain requirements, within my form use the amount which should not exceed a certain limit previously defined.

This is the validation that I would like to do, if it fulfills the validation, save it otherwise return the form with an error message.

Update

This would be the code of my form:

class ProductoForm(forms.ModelForm):
    class Meta:
        model = Producto
        fields =[
            'nombre',
            'imagen',
            'descripcion',
            'precio',
            'iva_1',
            'iva_2',
            'iva_3',
            'cantidad',
            'cantidad_minima',
            'codigo',
            'cod_auxiliar',
            'medida',
            'bodega',
            'espacio',
            'proveedor',
            'categoria',
            'estado',
            'lote',
            'fec_fabricacion',
            'fec_caducidad',
        ]
        labels = {
            'nombre':'Nombre',
            'imagen':'Imagen',
            'descripcion':'Descripción',
            'precio':'Precio',
            'iva_1':'Impuesto 1',
            'iva_2':'Impuesto 2',
            'iva_3':'Impuesto 3',
            'cantidad':'Cantidad',
            'cantidad_minima':'Stock  minimo',
            'codigo':'Código Fabricante',
            'cod_auxiliar': 'Código Auxiliar',
            'medida':'Medida',
            'bodega':'Bodega',
            'espacio':'Espacio',
            'proveedor':'Proveedor',
            'categoria':'Categorias',
            'estado':'Estado',
            'lote': 'Lote',
            'fec_fabricacion': 'Fec. Fabricación',
            'fec_caducidad':'Fec. Caducidad',
        }
        widgets = {
            'nombre':forms.TextInput(attrs={"class":"text-capitalize form-control", 'required':'required'}),
            'descripcion':forms.TextInput(attrs={"class":"form-control", 'required':'required'}),
            'precio': forms.TextInput(attrs={"class": "form-control", 'required':'required'}),
            #'iva': forms.TextInput(attrs={'class': 'form-control input-sm', 'required':'required'}),
            'cantidad':forms.TextInput(attrs={"class":"form-control", 'required':'required'}),
            'cantidad_minima':forms.TextInput(attrs={"class":"form-control", 'required':'required'}),
            'codigo':forms.TextInput(attrs={"class":"form-control", 'required':'required'}),
            'cod_auxiliar':forms.TextInput(attrs={"class":"form-control", 'required':'required'}),
            'medida':forms.Select(attrs={"class":"form-control", 'required':'required'}),
            'bodega':forms.Select(attrs={"class":"form-control", 'required':'required'}),
            'espacio': forms.Select(attrs={"class": "form-control", 'required': 'required'}),
            'proveedor':forms.Select(attrs={"class":"form-control", 'required':'required'}),
            'lote': forms.TextInput(attrs={"class": "form-control", 'required':'required'}),
            'fec_fabricacion': forms.TextInput(attrs={"class": "form-control", 'required':'required', 'type':'date'}),
            'fec_caducidad': forms.TextInput(attrs={"class": "form-control", 'required':'required', 'type':'date'}),
            'estado': forms.Select(attrs={"class": "form-control"})
        }

The quantity of the product must be validated based on a parameter set in space of the products. The model is:

class Espacio(models.Model):

    nombre = models.CharField(max_length=100)
    descripcion = models.CharField(max_length=300)
    codigo = models.CharField(max_length=100)
    fila = models.ForeignKey(Fila, on_delete=models.CASCADE)
    columna = models.ForeignKey(Columna, on_delete=models.CASCADE)
    cantidad_minima = models.IntegerField(null=True)
    cantidad_maxima = models.IntegerField(null=True)
    estado = models.IntegerField(choices=estado_choices, default=Activo)

    #def __str__(self):
    #    return self.nombre +self.fila + self+columna
    def __str__(self):
        return '%s Fila(%s) Columna(%s)' % (self.nombre, self.fila, self.columna)
    
asked by Diego Avila 28.12.2018 в 16:44
source

1 answer

1

You can use the method clean() of the form to validate it:

class ProductoForm(forms.ModelForm):
    # ...

    def clean(self):
        cleaned_data = super(ProductoForm, self).clean()
        cantidad = cleaned_data.get('cantidad')
        espacio_id = cleaned_data.get('espacio')

        # En este punto no estoy seguro si "espacio" contiene el ID del espacio
        # o un objeto. Si es un ID entonces puedes hacer un query a la base de
        # datos
        espacio = Espacio.objects.get(id=espacio_id)

        if cantidad < espacio.cantidad_minima or cantidad > espacio.cantidad_maxima:
            raise forms.ValidationError(
                'La cantidad no es correcta'
            )

Now, keep in mind that errors created from the clean() method are accessible from form.non_field_errrors . Therefore, in your template you should show them like this:

{% if form.non_field_errors %}
    {% for error in form.non_field_errors %}
        {{ error }}
    {% endfor %}
{% endif %}
    
answered by 28.12.2018 / 18:25
source