你在正确的轨道上。这是我对 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>
› <a href="{% url 'admin:app_list' app_label='users' %}">{% trans "Users" %}</a>
› <a href="{% url 'admin:users_user_changelist' %}">{% trans "Users" %}</a>
› <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 %}, {% 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
.