django管理员向用户发送电子邮件

时间:2019-10-22 02:01:30

标签: html django

\ admin.py

@admin.register(ParentsProfile)
class ParentsProfile(admin.ModelAdmin):
    list_display = ('Father_Email','Fathers_Firstname' , 'Fathers_Middle_Initial', 'Fathers_Lastname', 'Request')
    ordering = ('Request',)
    search_fields = ('Request',)
    actions = ['Send_Email','Send_Email_Disapproved']
    def Send_Email(self, request, queryset):
        html_content = "Your Registration has been approved.\n\nPlease use this %s as your username and %s as your password. \nYou may now start enrolling your student using this link https://...../Plogin_form/ \n\n\n REGISTRAR "
        for profile in queryset:
            send_mail(subject="Invite", message=html_content %(profile.Father_Email,profile.Parent_Password), from_email=settings.EMAIL_HOST_USER,
                       recipient_list=[profile.Father_Email])  # use your email function here
    def Send_Email_Disapproved(self, request, queryset):
        # the below can be modified according to your application.
        # queryset will hold the instances of your model
        for profile in queryset:
            send_mail(subject="Invite", message="Our Apology,\n\n Your Registration has been Disapproved " + profile.Father_Email + "\n\n\n REGISTRAR" + "", from_email=settings.EMAIL_HOST_USER,
                       recipient_list=[profile.Father_Email])

我有此代码可以向用户发送电子邮件,如何将html_content转换为HTML?这样我就可以向用户设计消息了?

enter image description here  它会像这样向用户gmail发送

1 个答案:

答案 0 :(得分:0)

您可以使用django.template.loader.render_to_string

进行渲染

您首先需要将模板存储在模板文件夹中,例如:

<!-- your_app/templates/my_template.html -->
<h1>hello, {{ user.first_name }}</h1>

然后在您的代码中,将html_content更改为

html_content = render_to_string('my_template.html', {
    'user': User.objects.get(username="some_username")
})

文档:https://docs.djangoproject.com/en/2.2/topics/templates/#django.template.loader.render_to_string