How to update a model which contains m2m field django?

125 views Asked by At

I have the following model, from which I created a ModelForm. I included the save_m2m because it was not saving the many to many fields when I was submitting the form. I also use 2 different views to create or update because I thought this was what was causing the creation of a new record.

However, instead of updating the instance, it creates a new one. So how can I edit a model's data which contains many to many fields?

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

There are 0 answers