0

I'm trying to pass a check-box selection from the template to the view for an email function. Each check-box in the template corresponds to a category in the database.

Contacts Database is like this:

NAME | CATEGORY | EMAIL
john |    man   | john@example.com
sue  |    woman | bob@example.com
spot |    dog   | dog@example.com

I want to email contacts based on category. The form will look a bit like this:

Target Audience: men[] women[] dogs[]
Subject: 
Message:

The target audience is selected by checking one or more check-boxes, this selection list is then passed to the view, where I can pass it through an email function as a list of recipients. What step am I missing here?

I have a form below which I think might work but my mind is exhausted at this point.

class EmailForm(forms.Form):

    CATEGORY_CHOICES = (
    ...
    )
    subject = forms.CharField(required=True)
    message = forms.CharField(required=True)
    from_email = forms.CharField()
    targetAudience = forms.MultipleChoiceField(choices=CATEGORY_CHOICES,
                                    widget=widgets.CheckboxSelectMultiple())

Ultimately I need to use the checkboxes to define the TargetAudience in the view, and do something like the following.

group = contact.objects.get(category==TargetAudience)

list = group.objects.values_list('email')

`send_mail`(mass mailing up to a few hundred) to this list.

EDIT: The view put together

def email_test(request):
    if request.method == 'GET':
        form = EmailForm()
    else:
        form = EmailForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            from_email = form.cleaned_data['from_email']
            targetaudience = form.cleaned_data['targetAudience']
            target_audience = contacts.objects.get(category=targetaudience)
            email_list = target_audience.objects.values_list('email', flat=True)
            send_mail(subject, message, from_email, email_list)
tim
  • 379
  • 2
  • 5
  • 14
  • `values_list` will give you list of tuples by default, pass `flat=True` as keyword argument into `values_list` if you want just list of e-mails. – GwynBleidD Oct 27 '15 at 16:14

1 Answers1

0

Assuming form.cleaned_data['targetAudience'] returns a list of categories, you could do something like:

email_list = Contact.objects.filter(category__in=targetaudience).values_list('email', flat=True)
Nathan Villaescusa
  • 17,331
  • 4
  • 53
  • 56