purpleSun
purpleSun

Reputation: 95

QuerySet confusion in Django Admin

Very new to Django/Python, and I've hit a brickwall after reading tons of documentation and posts regarding this issue...

So I'm working on a simple Django app that has a SQLlite database/table of Names and E-Mail addresses. I want to be able to send an e-mail from the admin panel, and use the name and e-mail address from the checkbox I select for a given name/address combo. The table itself works fine, as I can send the e-mails from other views on my site.

I'm working on making a custom admin action to do so, which I think is the correct way to go about this...

I thought I understood what the queryset argument is for and how it functions, but no matter what I do, I get an 'QuerySet' object has no attribute 'name' error. Clearly I have no idea how queryset works in an admin action.

from django.contrib import admin
from email_check.models import employeeEmail
from django.template import loader, Context
from django.core.mail import send_mail


class employeeEmail_Admin(admin.ModelAdmin):
    list_display = ('name', 'address')
    actions = ['resend_message']

    def resend_message(self, request, queryset):
        for employeeEmail.address in queryset:
            message = loader.get_template('email.txt')
            messageContext = Context({
                'name': queryset.name
            })
            send_mail('Test Subject Line', message.render(messageContext), '[email protected]', [queryset.address],
                      fail_silently=False)

admin.site.register(employeeEmail, employeeEmail_Admin)

I realize this is a bit vague, but basically I'm hoping to figure out how to access the name and address attributes from my employeeEmail model/table so I can send emails from the admin panel. Where I have queryset.name and [queryset.address], those are just example placeholders as I've tried numerous different things without success, and I'm guessing I'm nowhere near a solution.

Upvotes: 1

Views: 169

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

That's not quite how Python for loops work. You want something like:

    for employee in queryset:
        message = loader.get_template('email.txt')
        messageContext = Context({
            'name': employee.name
        })
        send_mail('Test Subject Line', message.render(messageContext), '[email protected]', [employee.address],
                  fail_silently=False)

The point is that queryset provides multiple instances of your employeeEmail model. When you run a for loop over the queryset, employee gets bound to each of them in sequence.

Upvotes: 2

Related Questions