-1

Please I have the model and the view below but I want a situation in which any value entered in the quantity field would be saved as a negative number in my database.

views.py

def post(self, request):
    receiveform = ReceiveForm(request.POST or None)
    stockform = StockForm(request.POST or None)
    if request.method == 'POST':
       
        if receiveform.is_valid() and stockform.is_valid():
            receiveform.save()
            stockform.save()
            messages.success(request,('Data save succefully'))
            return redirect('dashboard')
        else:
           print(receiveform.errors)

    receiveform = ReceiveForm(request.POST or None)
    context = {
      'receiveform':receiveform,
      'stockform':stockform,
     
    }
    return render(request, 'storesapp/receives.html', context)

models.py

class Receives(models.Model):
    date = models.DateField(default=now)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    quantity = models.IntegerField(default='0', blank=True, null=True)
Selcuk
  • 57,004
  • 12
  • 102
  • 110
fred
  • 151
  • 1
  • 12

1 Answers1

0

You can modify any model attributes before you actually save the form using commit=False. Replace the following line

receiveform.save()

with this

receives_instance = receiveform.save(commit=False)
receives_instance = -abs(receives_instance.quantity)
receives_instance.save()

The abs will ensure that any negative value submitted by the user will not be accidentally converted to positive.

Selcuk
  • 57,004
  • 12
  • 102
  • 110