Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom actions in Django Admin

in my Django app i have a Newsletter model. Now I'd like to be able to send the newsletter (and even resend it) from Django Admin.

I could do this with a hook on the Model.save() method but is there another way that is not tied to the Model?

Thanks

like image 725
Lorenzo Avatar asked Apr 06 '09 22:04

Lorenzo


People also ask

What are actions in Django?

Action functions are regular functions that take three arguments: The current ModelAdmin. An HttpRequest representing the current request, A QuerySet containing the set of objects selected by the user.

What we can do in admin portal in Django?

The Django admin application can use your models to automatically build a site area that you can use to create, view, update, and delete records. This can save you a lot of time during development, making it very easy to test your models and get a feel for whether you have the right data.


3 Answers

Admin actions allow you to easily hook up custom actions which can be performed on selected items from the admin's list pages.

like image 127
Jonny Buchanan Avatar answered Oct 25 '22 03:10

Jonny Buchanan


If you are doing it from the admin then you'll need to override the save() method, but it can be the AdminModel save... doesn't need to be the full Model save.

However, if you are emailing a lot of emails, a better approach would be to install django-mailer which puts emails into a queue for later processing and then provides you with a new management command: send_mail.

So once you're ready to send the newsletter out you can manually run python manage.py send_mail. Any emails with errors will be moved to a deferred queue where you can retry sending them later.

You can automate this by running manage.py send_mail from cron.

If you really want to get fancy and do it from admin site, install django-chronograph and set up your send_mail schedule from there.

like image 24
Van Gale Avatar answered Oct 25 '22 04:10

Van Gale


you can try this https://www.youtube.com/watch?v=WvL1cR2MgLI

just change

 def available (modeladmin,request,queryset):
    queryset.update(status='ava')

def not_available (modeladmin,request,queryset):
    queryset.update(status='not')

to something like

def send(modeladmin, request, queryset):

    for data in queryset:

        subject=data.title
        message=data.mesage
       

        for d in Users.objects.filter(newsletter=True):
            email=d.email
            


            sendemail = EmailMessage(subject, message+unsubscribe,    '[email protected]',
                [email], [],
                headers = {'Reply-To': '[email protected]'})

            sendemail.content_subtype = "html" 
            
            sendemail.send()
like image 26
blaz1988 Avatar answered Oct 25 '22 04:10

blaz1988