Django Form If condition in view.py with 2 instance

女生的网名这么多〃 提交于 2020-08-06 05:16:38

问题


TO SAVE DATA that is inputted in form in Django i tried tomake it like this I put this in my model.py

class Item(models.Model):
    CATEGORY = (
        ('Gudang Kering', 'Gudang Kering'),
        ('Gudang Basah','Gudang Basah'),
        )
    name = models.CharField(max_length=200,null= True)
    stock = models.IntegerField(default='0', blank=False, null=True)
    category = models.CharField(max_length=200,null= True,choices=CATEGORY)
    reorderlevel = models.IntegerField(default='0', blank=False, null=True)
    maxreorderlevel = models.IntegerField(default='0', blank=False, null=True)
    description = models.CharField(max_length=200,null= True, blank= True)
    date_created = models.DateTimeField(auto_now_add= True)
    tags = models.ManyToManyField(Tag)
    
    def __str__(self):
        return self.name

class Issue(models.Model):
    STATUS = (
        ('Pending', 'Pending'),
        ('Granted','Granted'),
        ('Denied','Denied'),
        )
    customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL)
    item = models.ForeignKey(Item, null=True, on_delete= models.SET_NULL)
    quantity = models.IntegerField(default='0', blank=False, null=True)
    date_created = models.DateTimeField(auto_now_add=True, auto_now=False)
    status = models.CharField(max_length=200,null= True, choices=STATUS)

Then in view.py i define the form like this

def updateIssue(request, pk):
    issue = Issue.objects.get(id=pk)
    item = Item.objects.all()
    form = UpdateIssueForm(instance=issue)
    if request.method == 'POST':
        form = UpdateIssueForm(request.POST,instance=issue)
        #print ('printing:',request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            if instance.status == 'Granted':
                item.stock -= instance.quantity
                instance.save()
                item.save()
            else:
        instance.save()

        return redirect('/')
    

    context = {'form':form}
    return render(request,'accounts/issue_form.html',context)``

The Goal
if instance == "Granted"
the item.stock will be decreased on the amount of instance.quantity and will be saved.
else
instance will just be saved without affecting the stock from the 2nd model

The error

    item = Item.objects.all()

even when called the item.stock have 0 attribute even when i have input data in database for that table

来源:https://stackoverflow.com/questions/63043875/django-form-if-condition-in-view-py-with-2-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!