[Fixed]-Django relationship in manyToMany models, object has no attribute

0👍

You just forgot a step:

def newECG(request, procedure_id):
    if request.method == 'POST':
        form = NewECG(request.POST)
        if form.is_valid():
            ecg = form.save()
            info = IncomingProcedure.objects.get(id=procedure_id)
            ecg.procedure.add(info) #HERE IS A PROBLEM
            return HttpResponseRedirect('/system/')
👤2ps

1👍

The ModelForm instance does not have the procedure attribute that is defined on the model. The ECG model instance, however, which is returned by the form’s save(...) method, does have it:

ecg_instance = form.save()
info = IncomingProcedure.objects.get(id=procedure_id)
# info = Procedure.objects.get(id=procedure_id)
ecg_instance.procedure.add(info)

0👍

I can’t understand why you are trying to add IncomingProcedure.objects to your from in views.py

If you want save it on your database, Should simply do this:

views.py

# ... Your codes:
M = form.save()  # save your class instance to M variable
info = IncomingProcedure.objects.get(id=procedure_id)
M.procedure.add(info) # save procedure instance to your object(An ECG model instance)

Leave a comment