11

我正在寻找一种从 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 管理操作页面,它有一个空的文本输入字段,我可以在其中编写一条新消息以每次发送?

如何才能做到这一点?我正在寻找一个不开放且通用的详细答案。

4

2 回答 2

12

你在正确的轨道上。这是我对 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.

于 2017-01-27T01:00:34.973 回答
1

您需要在您的管理类中编写一个自定义管理视图,该视图将呈现您想要的表单。要为此视图定义 URL 您需要覆盖该ModelAdmin.get_urls()方法。Django 文档简要提到了这一点,但有关更多详细信息,我建议您查看 Django Admin 的源代码(文件django/contrib/admin/sites.py)。

于 2013-09-04T17:24:18.283 回答