I am running a program that consists of sales.
I want that when registering a sale, if there is not enough stock of the requested product, an error appears indicating that there is no stock.
I was able to do it but I get the ValidationError like this:
Now I'm going to leave the form I made and the view:
forms.py:
class VentasForm(forms.ModelForm):
"""Formulario modelo de ventas."""
class Meta:
"""Meta class."""
model = Venta
fields = ('fecha', 'cliente', 'producto', 'cantidad', 'forma_pago')
def save(self):
"""Restar stock."""
data = super().clean()
producto = Product.objects.get(id=data['producto'].pk)
verificar_stock = producto.cantidad - float(data['cantidad'])
if verificar_stock >= 0:
producto.cantidad -= float(self.data['cantidad'])
producto.save()
else:
raise forms.ValidationError('No hay suficiente stock del producto.')
views.py:
class CreateVentasView(CreateView):
"""Registrar venta."""
template_name = 'ventas/create.html'
form_class = VentasForm
success_url = reverse_lazy('ventas:list')
context_object_name = 'venta'
And the template is only made with a{{ form.as_p }}
You should add a return to the end of the save function and add a clean function.
I leave the code: