save()生成新条目而不是更新Django

时间:2015-10-14 17:11:03

标签: python django

我不明白为什么,但是一个实例总是被创建复制我正在编辑的那个。另外,正如我所看到的,我正在使用的FormSet没有"实例"要添加到其构造函数的参数。无论如何,问题是当我编辑对象时,会生成Offer和OfferItem的实例。

def manage_offer(request, number=None):
    param_offer = Offer.objects.filter(id=number).first()
    param_items = OfferItem.objects.filter(offer=param_offer).values()

if request.method == 'POST':
    offer_form = OfferForm(request.POST, instance=param_offer)
    item_formset = OfferItemFormSet(request.POST, initial=param_items)

    if offer_form.is_valid() and item_formset.is_valid():

        # User selected go back and correct something
        if request.POST.get('back', False):

            return render(request,
                          'offer_edit.html',
                              {
                                  'forms': offer_form,
                                  'formset': item_formset,
                                  'offer_edit': True,
                              })

        # Proceeds with either saving or submitting request

        offer = offer_form.save(commit=False)
        offer.tax = offer_form.cleaned_data['tax'].value

        #Sotres items to be sent back to commit part
        offer_items = []
        #Gets the items from the form and stores them to conf. page
        for item_in_formset in item_formset.forms:
            item = item_in_formset.save(commit=False)
            item.item_code = get_item_code(item_in_formset.cleaned_data['name'])
            item.type = get_item_type(item_in_formset.cleaned_data['name'])
            offer.update_total(item.calc_total())
            # Adds items into list for invoice_ready page
            offer_items.append(item)

        # Request goes to confirmation page
        if request.POST.get('proceed', False):

            return render(request,
                          'offer_edit.html',
                              {
                                  'offer_form': offer_form,
                                  'item_formset': item_formset,
                                  'offer_ready': True,
                                  'offer': offer,
                                  'items': offer_items,
                              })
        # Passes confirmation page and saves offer
        offer.save()
        # Makes sure the value is correct by recalculating
        offer.reset_total()

        for obj_item in offer_items:
            obj_item.offer = offer
            offer.update_total(obj_item.calc_total())
            #commits to DB
            offer.save()
            obj_item.save()

        return render(request,
                      'offer_edit.html',
                          {
                              'success_add_offer': True,
                              'offer': offer,
                          },
                     )

# GET generates a blank or instanced page
else:
    offer_form = OfferForm(initial=
                               {'company': Company.objects.filter(is_default=True).first(),
                                'tax': Tax.objects.filter(is_default=True).first()
                                }, instance=param_offer)
    item_formset = OfferItemFormSet(initial=param_items)

return render(request, 'offer_edit.html',
              {
                  'forms': offer_form,
                  'formset': item_formset,
                  'edit_offer': number,
              })

Forms.py

class OfferItemForm(ModelForm):

class Meta:
    model = OfferItem
    # Some widgets and stuff ...

class RequiredFormSet(BaseFormSet):
    def __init__(self, *args, **kwargs):
        super(RequiredFormSet, self).__init__(*args, **kwargs)
        for form in self.forms:
            form.empty_permitted = False

OfferItemFormSet = formset_factory(OfferItemForm, formset=RequiredFormSet)

1 个答案:

答案 0 :(得分:0)

我发现了问题:因为我使用相同的View功能来编辑或添加新条目,所以在我的模板表单上我必须确保我也在识别是否正在编辑,因为该函数需要一个参数如果我正在编辑。在这种情况下,我必须更改帖子表单中的URL。

只是一个愚蠢的错误,花了我几个小时才发现。