使用表单字段更新Django模型

时间:2013-09-22 20:09:51

标签: python django django-models django-forms

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

FROM 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,
    })

FROM MODELS.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']

FROM URLS.PY

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

1 个答案:

答案 0 :(得分: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,
        })