Robby
Robby

Reputation: 193

django 1.10 get individual objects out of query

I have a model set up for subscribers to get on our mailing list. Whenever a new blog post is created I want to email the user. How do I get individual email addresses and first names from the model to use to email, each person individually? I want their first name to be in the email.

Here is my models.py:

class EmailUpdates(models.Model):
    email = models.EmailField(max_length=100, blank=True, unique=True)
    first_name = models.CharField(max_length=100, blank=True)

    def __str__(self):
        return self.email

    def __unicode__(self):
        return self.email

Here is my views.py:

def post_create(request):
    if not request.user.is_staff or not request.user.is_superuser:
        raise Http404()

    notification_subscribers = EmailUpdates.objects.all()
    form = PostForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user
        instance.save()
        messages.success(request, "Successfully Created")
        for user in notification_subscribers:
            user.first_name = notification_subscribers.filter('first_name')
            user.email = notification_subscribers.filter('email')
            user_data = {
                'user_email': user.email,
                'user_first_name': user.first_name,
            }
            plaintext = get_template('email/post_create_email/email_text.txt')
            htmly = get_template('email/post_create_email/email_template.html')
            text_content = plaintext.render(user_data)
            html_content = htmly.render(user_data)

            subject = "{0}, a new blog post has been made, Hurray!".format(user.first_name)
            from_email = '[email protected]'
            to_email = user.email
            msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email])
            msg.attach_alternative(html_content, "text/html")
            msg.send()
        return HttpResponseRedirect(instance.get_absolute_url())

    context = {
        "form": form,
    }
    return render(request, "posts/post_form.html", context)

Upvotes: 0

Views: 48

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599788

You're doing some bizarre unnecessary things in your loop. user is already the relevant instance of EmailSubscriber; it already has first_name and email attributes. You don't need to set them, you just use them.

Upvotes: 1

Related Questions