2016-03-30 152 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或類似的,以避免陰影/混亂。