简体   繁体   中英

Subtracting from a IntegerField field in django

I am a medical technologist trying to build an inventory program for my laboratory. My goal is to have a table that shows all of the reagents we have in a particular section of the lab and then display it to the user. I have been able to accomplish this by using django-tables2. What I would like to do next is have a form that allows the user to select the reagent they take out, then the quantity which they took out, submit the form and then have whatever quantity they took be subtracted from the total reagent count of that particular reagent. Here is what I have so far. Any help is appreciated!

forms.py
from django import forms
class ReagentCheckoutForm(forms.ModelForm):
    reagent_name= forms.CharField()
    amount_taken= forms.IntegerField()

models.py
class Inventory(models.Model):

    reagent_name= models.CharField(max_length=30)
    reagent_quantity= models.IntegerField()

views.py
def reagent_checkout(request):
    if request.method == 'POST':
        form= ReagentCheckoutForm(request.POST)
        if form.is_valid():
            form.save()
            reagent_name= form.cleaned_data['reagent_name']
            amount_taken= form.cleaned_data['amount_taken']

Just add this:

if form.is_valid():
    form.save()
    reagent_name= form.cleaned_data['reagent_name']
    amount_taken= form.cleaned_data['amount_taken']
    # get the reagent object
    reagent = Inventory.objects.get(reagent_name=reagent_name)
    # reduce quantity
    reagent.reagent_quantity -= amount_taken
    # save the object
    reagent.save()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM