Many to many field does not save in the main object

48 views
Skip to first unread message

Annick Sakoua

unread,
Aug 25, 2020, 9:57:48 AM8/25/20
to Django users
Hi all,
Please Helppppp.
I have been on this problem for 2 weeks now :(
I have an object: customer  that has 1 manytomany relationship with another object: gp.
I created some gp instances in the admin page. When I select one gp in the select dropdown list of existing gp  in my addcustomer form and submit my form, the form is saved with all the information except the gp selected. I only get the this: app.GeneralPractitioner.None  
Here are bellow my different classes. 

Thank you for your help :)

model.py

class Customer(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
gp = models.ManyToManyField(GeneralPractitioner, help_text="Select your general practitioner", related_name="customer")


class GeneralPractitioner(models.Model):
name = models.CharField(
max_length=40,
help_text="Enter the gp name)"
)
contact= models.CharField(max_length=11)

def __str__(self):
return self.name

in view.py

@login_required
def add_customer(request):
if request.method == 'POST':

form = AddCustomerForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
for item in instance:
item.save()
form.save_m2m()
instance.author = request.user

messages.success(request, f'Your form has been created!')
return redirect('addcustomer')
else:
form = AddCustomerForm()
return render(request, 'app/addcustomer.html', {'form': form})

customer_details.html

{% extends "app/base.html" %}
{% load crispy_forms_tags %}
{% block content %}

<div>
<p>Firstname: {{customer.first_name}}</p>
<p>Lastname: {{customer.last_name}}</p>
<p>General practitioner: {{customer.gp}}</p>
</div>

Annick Sakoua

unread,
Aug 28, 2020, 6:54:56 AM8/28/20
to Django users
 I found the mistake, I removed the 'for item in instance'  in my addcustomer function and Elesire suggestion about iterating in the {{customer.gp}} object  in my template helped me a lof. Thank you soo much.
Reply all
Reply to author
Forward
0 new messages