如何更新包含m2m字段django的模型?

时间:2016-12-26 19:43:29

标签: django django-forms manytomanyfield updatemodel

我有以下模型,我从中创建了一个ModelForm。 我包含了save_m2m,因为在我提交表单时它没有保存多个字段。 我还使用2个不同的视图来创建或更新,因为我认为这是导致创建新记录的原因。

但是,它不是更新实例,而是创建一个新实例。 那么如何编辑包含多个到多个字段的模型数据呢?

models.py

class GeneralContract(models.Model):

    idcontract = models.IntegerField(primary_key=True)
    client=models.ForeignKey(Person)
    issuedate = models.DateTimeField()  # Field name made lowercase.
    plan = models.ManyToManyField(Generalbusinessplans)
    annualpremium = models.FloatField()  # Field name made lowercase.
    doses = models.IntegerField(blank=True, null=True)

views.py

def addContractGeneralView(request):

    added=False
    if request.method == 'POST':
        contract_form = GeneralContractForm(request.POST)
        if contract_form.is_valid():
            profile = contract_form.save(commit=False)
            p = Person.objects.get(idperson=contract_form.cleaned_data['client'].idperson)
            print p
            if p.isclient == 0:
                print 'in if'
                p.isclient = 1
                p.save()
            profile.save()
            contract_form.save_m2m()
            print profile.plan
            added = True
        else:
            print contract_form.errors
    else:
        contract_form = GeneralContractForm()
    return render(request,
            'leadsMasterApp/addContractGeneral.html',
            {'add_contract_form':contract_form,'added': added})


def editContractGeneralView(request,pk):

    instance=get_object_or_404(GeneralContract, pk=pk)
    added=False
    if request.method == 'POST':
        contract_form = GeneralContractForm(request.POST,instance=instance)
        if contract_form.is_valid():
            profile = contract_form.save(commit=False)
            p = Person.objects.get(idperson=contract_form.cleaned_data['client'].idperson)
            print p
            if p.isclient == 0:
                print 'in if'
                p.isclient = 1
                p.save()
            profile.save()
            contract_form.save_m2m()
            print profile.plan
            added = True
        else:
            print contract_form.errors
    else:
        contract_form = GeneralContractForm(instance=instance)
    return render(request,
            'leadsMasterApp/addContractGeneral.html',
            {'add_contract_form':contract_form,'added': added})

0 个答案:

没有答案