2016-03-30 153 views
1

我已经包含隐藏输入标签,当我发布形式的意见和打印表格,我看到我需要的值,但内容没有保存到数据库中 这里是我的HTML保存HTML输入标签Django模型

<form method="POST" action="/selly/cart/" item_id="{{product.pk}}" enctype="multipart/form-data"> 
    {% csrf_token %} 
    <h1 name="description">Description is : {{each_item.description}}</h1> 
    <p><input type="hidden" name="description" value="{{each_item.description}}"></p> 

    <span name="price">Price is : $ {{each_item.price}}/piece</span> 
    <p><input type="hidden" name="price" value ="{{each_item.price}}"></p> 

    <p>Quantity is : <input type="number" default="0" name="quantity"> piece ({{each_item.item_remaining}} pieces available)</p> 
    <br> 
    <input type="submit" class="btn btn-primary" value="Add to Cart"> 

</form> 

这里是我的views.py

from selly.models import Cart 
def cart(request): 
    if request.method == "POST": 
     print "rp ", request.POST 

     description = request.POST['description'] 
     print "Description is ", description 

     price = request.POST['price'] 
     print "Price is ", price 

     quantity = request.POST['quantity'] 
     print "Quantity is ", quantity 

     items = Cart.objects.get_or_create(client="client", description="description", price="price", quantity="quantity") 
     print "ITEMS", items 
    return render(request, 'selly/cart.html', {'items': items}) 

这里是model.py

class Cart(models.Model): 
    description = models.CharField(max_length = 100) 
    price = models.DecimalField(max_digits=10, decimal_places=2) 
    quantity = models.IntegerField() 

    def __str__(self): 
     return self.description 

    def total(self): 
     return self.price * self.quantity 

有使其保存到数据库中,我创建名为车的方式

+0

只需调用save方法:'items.save()' – Selcuk

+0

@Selcuk获取[u''价格'值必须是十进制数。“]作为错误 – uche

+0

您输入了什么价格值? – v1k45

回答

1

我很惊讶你不代码得到一个错误 - get_or_create返回一个元组,每个文档:

返回(对象,创建的),其中,对象是检索或 创建的对象和创建是一个布尔值指定一个新的 对象是否已创建的元组。

所以你行items = Cart.objects.get_or_create(client="client", description="description", price="price", quantity="quantity")

需求是

items, created = = Cart.objects.get_or_create(client="client", description="description", price="price", quantity="quantity")

你也可以询问创建变量,因为如果它是假的,那么它并没有创造新对象;如果它没有创建新的对象,那么所有get_or_create正在做的是已经在数据库返回的对象。

您需要手动保存对象,如果你要更新它。

这是因为:

这意味着作为一个快捷方式boilerplatish代码。例如:

try: 
    obj = Person.objects.get(first_name='John', last_name='Lennon') 
except Person.DoesNotExist: 
    obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9)) 
    obj.save() 

全部细节的文档页面for get_or_create.

上。而且,你的最后一行是错误的 - 你要指定字符串对象,你做price="price" - 你真的想做price=price,因为你分配Øbject.price=price,这就是你叫上面的代码中的变量。我建议可能会调用这些变量的incoming_price或类似的,以避免阴影/混乱。