Formset is_valid删除django中的对象数据

时间:2017-10-30 16:50:59

标签: python django formset

我在formset的表单中使用django

我在代码中获取订单对象并获取全部数据对象但是当我调用formset.is_valid时,它会删除订单对象的所有数据并将它们设置为None或默认值。我不知道会发生什么。

这是views.py

def assign_order_to_printer(request, order_id):
    design_formset = forms.modelformset_factory(model=DesignAndColoration, extra=0,
                                            form=AddDesignAndColorationForm,
                                            fields=['print_machine', 'design_image',
                                                    'high_quality_design_image', 'width', 'height'],
                                            can_delete=True)
    order = Order.objects.get(id=order_id)
    if request.method == 'POST':
        form = AddOrderForm(request.POST, instance=order, enable=['print_machine'])
        formset = design_formset(request.POST, request.FILES, queryset=order.designandcoloration_set.all())
        if form.is_valid() and formset.is_valid():
            order = form.save(commit=False)
            order.status = order_status_assigned
            instances = formset.save(commit=False)
            for instance in instances:
                instance.order = order
                instance.save()
            order.save()
            for obj in formset.deleted_objects:
                obj.delete()
            return redirect(reverse('products:list_accepted_orders_pm'))
    else:
        form = AddOrderForm(instance=order, enable=['print_machine'])
        formset = design_formset(queryset=order.designandcoloration_set.all())
    return render(request, 'product_management/printer_manager_assign_printer.html', {
        'order': order,
        'form': form,
        'design_formset': formset,
    })

这是forms.py

class AddOrderForm(forms.ModelForm):

    class Meta:
        model = Order
        exclude = []
        widgets = {
            "status": forms.HiddenInput,
            "customer": Select2,
        }
        labels = {
            "status": ''
        }

    def __init__(self, *args, **kwargs):
        enable_fields = kwargs.pop('enable', None)
        disable_fields = kwargs.pop('disable', None)
        super(AddOrderForm, self).__init__(*args, **kwargs)
        if enable_fields is not None:
            for field_name, field in self.fields.items():
                if field_name not in enable_fields:
                    field.widget.attrs['disabled'] = True
        if disable_fields is not None:
            for field_name in disable_fields:
                self.fields[field_name].widget.attrs['disabled'] = True
        for field_name, field in self.fields.items():
            field.required = False

class AddDesignAndColorationForm(forms.ModelForm):

    class Meta:
        model = DesignAndColoration
        exclude = []
        widgets = {
            'design_image': forms.ClearableFileInput(attrs={'category': 'image'}),
            'high_quality_design_image': forms.ClearableFileInput(attrs={'category': 'image'})
    }


class AddDesignAndColorationFormSet(BaseFormSet):

    def clean(self):
        for form in self.forms:
            if not form.cleaned_data:
                form.add_error('design_image', 'فرم ناقص است.')
            elif 'design_image' not in form.cleaned_data:
                form.add_error('design_image', 'عکس طراحی وجود ندارد.')
            elif 'print_number' not in form.cleaned_data:
                form.add_error('print_number', 'تعداد وجود ندارد.')

0 个答案:

没有答案