我无法一次更新模型集中的多个数据

时间:2019-08-05 06:16:08

标签: django-forms

我已经用产品数据预先填充了表格,然后检索并进行编辑。我正在尝试编辑几行,然后一次性保存。

我有以下两种等级和产品模型

class Grade(models.Model): 
    GRADE_TYPES = (
        ("p", "Primary Grade"),
        ("S", "Secondary Grade"),
    )
    grade_name = models.TextField(max_length=10, unique = True)
    grade_type = models.CharField(max_length=1, choices=GRADE_TYPES)

class Meta:
    ordering = ['grade_name']

def __str__(self):
    return self.grade_name

def get_absolute_url(self):
    return reverse('grade_list')


class Product(models.Model): 
    production_date = models.DateField()
    grade = models.ForeignKey(Grade, on_delete=models.SET_NULL, null=True)
    kilos = models.DecimalField(decimal_places=1, max_digits = 5)
    products=[]

class Meta:
    unique_together =('production_date','grade')
    ordering = ['-production_date']


def __str__(self):
    return self.production_date

def get_absolute_url(self):
    return reverse('production_list')

我的表格

class Add_ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = '__all__'

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    product_date = datetime.today()-timedelta(days=1)
    grades = Grade.objects.all()   
    for grade in grades:
        product = Product.create(product_date,grade,0)
        product.save()

class Add_product(View):     
    template_name =  'create_daily_product.html'     
    Product_Formset = modelformset_factory(Product, form=Add_ProductForm)

    def get(self,request, *args, **kwargs):
        context ={
            'product_form':self.Product_Formset(queryset = 
             Product.objects.filter(kilos=0.0)),
        }
        return render(request,self.template_name,context) 

    def post(self,request, *args, **kwargs):
        product_formset = self.Product_Formset(self.request.POST)
        if product_formset.is_valid:
            for products in product_formset:
                products.save() # The Product could not be changed because 
                the data didn't validate.
            return HttpResponseRedirect(reverse("success.url"))                    
        else:
            context ={
                'product_form':self.Product_Formset(),
            }
            return render(request,'create_daily_product.html',context) 

我用初始数据填充模型Product,然后检索它,以便可以将千克数量更改为其他值。然后,我成功地编辑了公斤,但是单击更新以保存时,出现错误消息“由于数据未验证,产品无法更改”。该表格似乎有效,但是在开始保存时会失败。

我应该渲染数据进行编辑,更新然后保存。前两个成功发生,但不是最后一个。我还只想保存千位数> 0的行,但不能测试,因为保存失败。

1 个答案:

答案 0 :(得分:0)

可能是因为这条线
if product_formset.is_valid:

应该是
if product_formset.is_valid():

还要检查模型和模型形式中函数的缩进。
您的模型应该是

class Grade(models.Model): 
    GRADE_TYPES = (
        ("p", "Primary Grade"),
        ("S", "Secondary Grade"),
    )
    grade_name = models.TextField(max_length=10, unique = True)
    grade_type = models.CharField(max_length=1, choices=GRADE_TYPES)

    class Meta:
       ordering = ['grade_name']

    def __str__(self):
       return self.grade_name

    def get_absolute_url(self):
       return reverse('grade_list')


class Product(models.Model): 
    production_date = models.DateField()
    grade = models.ForeignKey(Grade, on_delete=models.SET_NULL, null=True)
    kilos = models.DecimalField(decimal_places=1, max_digits = 5)
    products=[]

    class Meta:
       unique_together =('production_date','grade')
       ordering = ['-production_date']


    def __str__(self):
       return self.production_date

    def get_absolute_url(self):
       return reverse('production_list')

在您的模型表单中:

class Add_ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = '__all__'

    def __init__(self, *args, **kwargs):
       super().__init__(*args, **kwargs)
       ......