我在这里尝试执行两项操作,删除或向选定的用户发送电子邮件。要发送电子邮件,将需要一个表格,因此我将选中的用户存储在这样的会话中,并在发送电子邮件后从会话中删除所有用户session['users'].clear()
。它说,即使我提供了sub和msg也是必需的。
此代码有什么问题?
删除正常运行的选定用户
def selected_users(request):
form = SendMailForm()
selected_users = get_user_model().objects.filter(id__in=request.POST.getlist('users'))
initial = {'users':[]}
session = request.session.get('users',initial)
if selected_users:
for user in selected_users:
if not user in session['users']:
session['users'].append(user.email)
print('hello1',session['users'])
if selected_users and request.method == 'POST' and 'delete_selected' in request.POST:
count = selected_users.count()
selected_users.delete()
messages.success(request, '{} users deleted.'.format(count))
return redirect('view_users')
elif request.method == 'POST' and 'mail_selected' in request.POST:
form = SendMailForm(request.POST or None)
config = EmailConfiguration.objects.order_by('-date').first()
backend = EmailBackend(host=config.email_host, port=config.email_port, username=config.email_host_user,
password=config.email_host_password, use_tls=config.email_use_tls)
if form.is_valid():
sub = form.cleaned_data['sub']
msg = form.cleaned_data['msg']
for email in session['users']:
email = EmailMessage(subject=sub, body=msg, from_email=config.email_host_user, to=[email],
connection=backend)
email.send()
# clearing users from session after email sends
session['users'].clear()
messages.success(request, 'Your mail sent.')
return redirect('view_users')
else:
print(form.errors)
return render(request, 'send_mail_selected.html', {'users': selected_users,'form':form,'session':session})
forms.py
class SendMailForm(forms.Form):
#to = forms.EmailField(required=False)
sub = forms.CharField(max_length=250)
msg = forms.CharField(widget=forms.Textarea)
模板
<form method="POST" >
{% csrf_token %
{{form.as_p}}
<button type="submit" class="btn btn-primary" name="mail_selected">Send </button>
</form>