2016-07-18 35 views
0

我是CS第一年,所以如果我完全不清楚,請原諒我的noobness。使用formset更新幾個對象

我有幾個對象來自我的「產品」模型。現在我想更新所有對象上的相同字段,不同值的'數量'字段。但是,與updateview中的每個產品的點擊和退出不同,我想列出所有產品併爲每個產品設置值,並同時更改它們。據我所見,「FormSet」應該做的訣竅?

我的分類模型看起來像這樣(指定的產品)

class Category(models.Model): 
    category = models.CharField(max_length=30) 

    def __str__(self): 
     return self.category 

我的產品型號如下:

class Product(models.Model): 
    title = models.CharField(max_length=200) 
    description = models.CharField(max_length=200) 
    category = models.ForeignKey(Category) 
    price = models.DecimalField(max_digits=5, decimal_places=2) 
    stock = models.PositiveIntegerField() 

    def __str__(self): 
     return self.title 

用於更新單品我的更新視圖看起來是這樣的:

class UpdateProductView(UpdateView): 
    model = Product 
    form_class = ProductForm 
    template_name = "product_form.html" 
    success_url = '/products' 

class CreateCategoryView(FormView): 
    template_name = "category_form.html" 
    form_class = CategoryForm 

我閱讀了關於formset的文檔,但我得承認我並沒有太多的感覺更聰明的如何實際使用它後...任何人都可以舉手?

回答

0

沒有找到您Product模型quantity領域,但我所看到的,你要使用ModelFormSet。

# Generate your formset class with `modelformset_factory` 
ProductFormSetClass = modelformset_factory(Product, fields=('quantity',)) 
# Now you can create your formset, bind data, etc 
formset = ProductFormSetClass(request.POST) 
formset.save() 

更多細節被鏈接: https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#model-formsets

另外,不要忘記檢查所有​​參數。

+0

Ahh yes of course,我的意思是'股票',而不是數量。 我是否將其定義爲一個獨立的功能,或者我是否對此做出新的看法?我發現它有點令人困惑:D – PaFko

+0

它的工作原理與Django中的表單一樣,可以綁定數據,使用.is_valid()方法驗證formset中的每個表單,但首先應該使用工廠創建類而不是聲明它。如果你真的想了解它是如何工作的,試着用簡單的視圖自己實現它。這裏的文檔示例https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#using-a-formset-in-views-and-templates然後,您可以嘗試使用'django的通用視圖-extra-views'應用程序 –