mercredi 1 juillet 2015

Django - Iterating Checkboxes from ManyToManyField then adding in Views

I'm making a program to let users create lists out of all of the contacts they have available. I'd like to have the entire list iterate with checkboxes, then in the views, add all the checked boxes to the Contact List's contacts list in one go.

I know how to iterate the checkboxes, but I don't know how to tell the views to check all the boxes to see which ones are checked, then add the associated user to the list.

In models.py:

class Organization(models.Model):
    users = models.ManyToManyField(User, related_name='organizations')

class Contact(models.Model):
    unique_id = models.IntegerField(default=1)
    email_address = models.CharField(max_length=50, null=True, blank=True)
    name = models.CharField(max_length=200, null=True, blank=True)

class ContactList(models.Model):
    unique_id = models.IntegerField(default=1)
    name = models.CharField(max_length=200, null=True, blank=True)
    contacts = models.ManyToManyField(Contact, related_name='contact_lists')

In contactlist.html:

<form action="/contactlists/add_contacts/ method="post">{% csrf_token %}
    {% for contact in contacts %}
        <p><input type="checkbox" name="contacts" value="{{contact.unique_id}}">{{contact.name}}</p>
    {% endfor %}
<input type="submit" name="submit" value="New Contact List">

In views.py:

def add_contacts(request, organization_id=1):
    organization = Organization.objects.get(id=organization_id)
    contacts = Contact.objects.all()
    args = {'contacts': contacts, 'organization': organization}
    args.update(csrf(request))
    return render(request, 'contactlist.html', args)

How would I tell my View to sort through the list of checkboxes, grab the IDs of any boxes that have been checked, then add those to the contacts ManyToManyField? I don't understand how to iterate that list.

If I were to be adding them one at a time by name through a text input, it could be as simple as:

def add_contacts(request, organization_id=1):
    if request.method == "POST":
        c = ContactListForm(request.POST)
        if c.is_valid():
            c.save()

but I'd like to instead display a list of all contacts, with checkboxes, then add the contact to the list if their checkbox is checked.




Aucun commentaire:

Enregistrer un commentaire