Muhammad Taqi
Muhammad Taqi

Reputation: 5424

Do Some work before Saving and After Saving data in django Admin

I have a model class ' Newsletters'. in which there is a choice for send to like student, teacher etc.

I want to get all email of student or teacher whatever the user selected, then after save button is pressed, get the id of currently saved newsletter and all the emails of selected choice student or teacher and save it into another table called email logs.

all these work is done on admin panel of django.

class newsletter(models.Model):
    newsletter_id = models.AutoField(primary_key=True)
    subject = models.CharField(max_length=512)
    content = RichTextField()
    send_to_choice = {('0', 'None'), ('1', 'Student'), ('2', 'Teacher')}
    send_to = models.CharField(max_length=128, choices=send_to_choice, default='None')
    created_on = models.DateTimeField(auto_now_add=True)
    created_by = models.EmailField(max_length=254)
    updated_on = models.DateTimeField(auto_now_add=True)
    updated_by = models.EmailField(max_length=254)

when admin select a choice then a query should be activated and show all emails for selected choice. I know the query, but didn't' know how to implement this on django admin panel.

UPDATED:

i wrote this simple function for testing that if it executes then add my logic to it.

def save_model(self, request, obj, form, change):
    obj.save()
    if not change:
        if obj.send_to == '1':
            messages.success(request, 'MyModel was saved!.')
            obj.created_by = '[email protected]'
    if obj.send_to == '1':
            messages.success(request, 'MyModel was saved!.')
            obj.created_by = '[email protected]'
    obj.save()

Upvotes: 0

Views: 2031

Answers (1)

catavaran
catavaran

Reputation: 45575

You have to override the ModelAdmin.save_model() method:

class NewsletterAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        obj.save()
        if not change: # newly created newsletter
            if obj.send_to == '1':
                for student in Student.objects.all():
                    EmailLog.objects.create(student=student, newsletter=obj)
            elif obj.send_to == '2':
                for teacher in Teacher.objects.all():
                    EmailLog.objects.create(teacher=teacher, newsletter=obj)

Upvotes: 2

Related Questions