2

我正在尝试使用前端的整数表单字段更新我的库存模型的数量。我可以添加新的库存项目,但我想更新现有项目。这是我的代码:

来自VIEWS.PY

def view_inventory(request, slug):

if request.method == 'POST':
    quantity_add = addQuantity(request.POST)
    if quantity_add.is_valid():
        cd = quantity_add.cleaned_data
        addq=Inventory(quantity = cd.get('quantity'))
        addq.save()

quantity_add=addQuantity()

return render(request, 'inv/view_inventory.html', {
    'item': get_object_or_404(Inventory.objects.all(), slug=slug),
    'form' : quantity_add,
    })

来自模型.PY

class Inventory(models.Model):
    quantity = models.IntegerField()
    name = models.CharField(max_length=150, unique = True)
    slug = models.SlugField(unique = True)
    date = models.DateTimeField(auto_now_add=True)
    description = models.CharField(max_length=250)
    category    = models.ForeignKey(Category, null=True, blank=True)
    def __unicode__(self):
        return self.name
    @permalink
    def get_absolute_url(self):
        return ('view_inventory', None, { 'slug' : self.slug })

    class Meta:
        ordering = ['-date']

来自 URLS.PY

url(r'^(?P<slug>[\w\-]+)/$', 'inv.views.view_inventory', name='view_inventory'),
4

1 回答 1

2

您只需要获取记录然后更新它:

 def view_inventory(request, slug):

  if request.method == 'POST':
        quantity_add = addQuantity(request.POST)
        if quantity_add.is_valid():
            cd = quantity_add.cleaned_data
            old_inventory = Inventory.objects.get(id=something here) #id or pk or whatever you want
            old_inventory.quantity = cd.get('quantity')
            old_inventory.save()

    quantity_add=addQuantity()

    return render(request, 'inv/view_inventory.html', {
        'item': get_object_or_404(Inventory.objects.all(), slug=slug),
        'form' : quantity_add,
        })
于 2013-09-22T21:46:17.980 回答