使用Django Admin操作发送批量电子邮件 [英] Using Django Admin Actions to send bulk emails

查看:156
本文介绍了使用Django Admin操作发送批量电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种通过Django Admin Action向用户发送批量电子邮件的方法.到目前为止,这是我所拥有的:

class MyUserAdmin(UserAdmin):
    list_display = ['username', 'email', 'first_name', 'last_name', 'is_active', staff]
    list_filter = ['groups', 'is_staff', 'is_superuser', 'is_active']
    actions = ['send_EMAIL']


    def send_EMAIL(self, request, queryset):
        from django.core.mail import send_mail
        for i in queryset:
            if i.email:
                send_mail('Subject here', 'Here is the message.', 'from@example.com',[i.email], fail_silently=False)
            else:
        self.message_user(request, "Mail sent successfully ") 
    send_EMAIL.short_description = "Send an email to selected users"

这很好,但是!我必须每次都对实际消息进行硬编码.如果我可以使它动态化怎么办?我不需要每次都发送大量电子邮件来更改来自admin.py的消息,而是为什么不创建一个中间Django管理员操作页面,该页面具有一个空的Text输入字段,我可以在其中编写一条新消息来发送一次呢?

这怎么办?我正在寻找一个非常详细的答案,而不是开放式的和通用的.

解决方案

您处在正确的轨道上.这是我对django管理员操作的实现,该操作使您可以向选定的用户写消息. (我知道这太迟了,但可能会对其他人有所帮助.)

发送电子邮件功能:

def send_email(self, request, queryset):
    form = SendEmailForm(initial={'users': queryset})
    return render(request, 'users/send_email.html', {'form': form})

send_email.html模板(我从django确认删除视图中借用了此标记,您可能想在这里做些不同的事情)

{% extends "admin/base_site.html" %}
{% load i18n admin_urls static %}


{% block bodyclass %}{{ block.super }} app-{{ opts.app_label }} model-{{ opts.model_name }} delete-confirmation{% endblock %}

{% block breadcrumbs %}
<div class="breadcrumbs">
<a href="{% url 'admin:index' %}">{% trans 'Home' %}</a>
&rsaquo; <a href="{% url 'admin:app_list' app_label='users' %}">{% trans "Users" %}</a>
&rsaquo; <a href="{% url 'admin:users_user_changelist' %}">{% trans "Users" %}</a>
&rsaquo; <span>Send email</span>
</div>
{% endblock %}

{% block content %}
<p>{% blocktrans %}Write your message here{% endblocktrans %}</p>
<form method="POST" action="{% url 'users:email' %}">{% csrf_token %}
    <div>
        <div>
            <p>{{ form.users.errors }}</p>
            <p>{{ form.users.label_tag }}</p>
            <p>
                {% for user in form.users.initial %}
                    {{ user.email }}{% if not forloop.last %},&nbsp;{% endif %}
                {% endfor %}
            </p>
            <select name="users" multiple style="display: none">
                {% for user in form.users.initial %}
                    <option value="{{ user.id }}" selected>{{ user }}</option>
                {% endfor %}
            </select>
        </div>
        <div>
            <p>{{ form.subject.errors }}</p>
            <p>{{ form.subject.label_tag }}</p>
            <p>{{ form.subject }}</p>
        </div>
        <div>
            <p>{{ form.message.errors }}</p>
            <p>{{ form.message.label_tag }}</p>
            <p>{{ form.message }}</p>
        </div>
        <input type="submit" value="{% trans 'Send message' %}" />
        <a href="{% url 'admin:users_user_changelist' %}" class="button cancel-link">{% trans "No, take me back" %}</a>
    </div>
</form>
{% endblock %}

发送电子邮件表单类:

class SendEmailForm(forms.Form):
    subject = forms.CharField(
        widget=forms.TextInput(attrs={'placeholder': _('Subject')}))
    message = forms.CharField(widget=forms.Textarea)
    users = forms.ModelMultipleChoiceField(label="To",
                                           queryset=User.objects.all(),
                                           widget=forms.SelectMultiple())

最后是发送电子邮件视图+ url conf:

# url pattern
url(
    regex=r'^email-users/$',
    view=views.SendUserEmails.as_view(),
    name='email'
),


# SendUserEmails view class
class SendUserEmails(IsStaff, FormView):
    template_name = 'users/send_email.html'
    form_class = SendEmailForm
    success_url = reverse_lazy('admin:users_user_changelist')

    def form_valid(self, form):
        users = form.cleaned_data['users']
        subject = form.cleaned_data['subject']
        message = form.cleaned_data['message']
        email_users.delay(users, subject, message)
        user_message = '{0} users emailed successfully!'.format(form.cleaned_data['users'].count())
        messages.success(self.request, user_message)
        return super(SendUserEmails, self).form_valid(form)

此实现对我来说效果很好.这是中间视图的样子:

如果您没有名为users的应用程序或名为User的模型,则可能必须更改模板中的一些内容,以在其中构建面包屑或视图的反向URL./p>

I'm looking for a way to send bulk emails to users from a Django Admin Action. This is what I have thus far:

class MyUserAdmin(UserAdmin):
    list_display = ['username', 'email', 'first_name', 'last_name', 'is_active', staff]
    list_filter = ['groups', 'is_staff', 'is_superuser', 'is_active']
    actions = ['send_EMAIL']


    def send_EMAIL(self, request, queryset):
        from django.core.mail import send_mail
        for i in queryset:
            if i.email:
                send_mail('Subject here', 'Here is the message.', 'from@example.com',[i.email], fail_silently=False)
            else:
        self.message_user(request, "Mail sent successfully ") 
    send_EMAIL.short_description = "Send an email to selected users"

This is fine but! I have to hardcode the actual message every single time. What if I could make it Dynamic? Instead of changing the message from the admin.py every single time I need to send a bulk email, why not create an intermediate Django admin action page that has a empty Text input field where I can write a new message to send every single time?

How can this be done? I'm looking for a well detailed answer that is not open ended and generic.

解决方案

You are on the right track. Here is my implementation of a django admin action that allows you to write a message to the selected users. (I know this is super late but might help someone else).

send_email function:

def send_email(self, request, queryset):
    form = SendEmailForm(initial={'users': queryset})
    return render(request, 'users/send_email.html', {'form': form})

send_email.html template (I borrowed the markup from the django confirm delete view for this you may want to do something different here):

{% extends "admin/base_site.html" %}
{% load i18n admin_urls static %}


{% block bodyclass %}{{ block.super }} app-{{ opts.app_label }} model-{{ opts.model_name }} delete-confirmation{% endblock %}

{% block breadcrumbs %}
<div class="breadcrumbs">
<a href="{% url 'admin:index' %}">{% trans 'Home' %}</a>
&rsaquo; <a href="{% url 'admin:app_list' app_label='users' %}">{% trans "Users" %}</a>
&rsaquo; <a href="{% url 'admin:users_user_changelist' %}">{% trans "Users" %}</a>
&rsaquo; <span>Send email</span>
</div>
{% endblock %}

{% block content %}
<p>{% blocktrans %}Write your message here{% endblocktrans %}</p>
<form method="POST" action="{% url 'users:email' %}">{% csrf_token %}
    <div>
        <div>
            <p>{{ form.users.errors }}</p>
            <p>{{ form.users.label_tag }}</p>
            <p>
                {% for user in form.users.initial %}
                    {{ user.email }}{% if not forloop.last %},&nbsp;{% endif %}
                {% endfor %}
            </p>
            <select name="users" multiple style="display: none">
                {% for user in form.users.initial %}
                    <option value="{{ user.id }}" selected>{{ user }}</option>
                {% endfor %}
            </select>
        </div>
        <div>
            <p>{{ form.subject.errors }}</p>
            <p>{{ form.subject.label_tag }}</p>
            <p>{{ form.subject }}</p>
        </div>
        <div>
            <p>{{ form.message.errors }}</p>
            <p>{{ form.message.label_tag }}</p>
            <p>{{ form.message }}</p>
        </div>
        <input type="submit" value="{% trans 'Send message' %}" />
        <a href="{% url 'admin:users_user_changelist' %}" class="button cancel-link">{% trans "No, take me back" %}</a>
    </div>
</form>
{% endblock %}

send email form class:

class SendEmailForm(forms.Form):
    subject = forms.CharField(
        widget=forms.TextInput(attrs={'placeholder': _('Subject')}))
    message = forms.CharField(widget=forms.Textarea)
    users = forms.ModelMultipleChoiceField(label="To",
                                           queryset=User.objects.all(),
                                           widget=forms.SelectMultiple())

And finally the send email view + url conf:

# url pattern
url(
    regex=r'^email-users/$',
    view=views.SendUserEmails.as_view(),
    name='email'
),


# SendUserEmails view class
class SendUserEmails(IsStaff, FormView):
    template_name = 'users/send_email.html'
    form_class = SendEmailForm
    success_url = reverse_lazy('admin:users_user_changelist')

    def form_valid(self, form):
        users = form.cleaned_data['users']
        subject = form.cleaned_data['subject']
        message = form.cleaned_data['message']
        email_users.delay(users, subject, message)
        user_message = '{0} users emailed successfully!'.format(form.cleaned_data['users'].count())
        messages.success(self.request, user_message)
        return super(SendUserEmails, self).form_valid(form)

This implementation worked fine for me. Here is what the intermediate view looks like:

You might have to change a couple of things in the template where I build out the breadcrumbs or the reverse url for the view in case you don't have an app called users or a model called User.

这篇关于使用Django Admin操作发送批量电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆