我正在尝试在管理员创建用户帐户后向用户发送电子邮件。
账户/ admin.py
class ProfileInline(admin.StackedInline):
model = Profile
can_delete = False
verbose_name_plural = 'Profile'
fk_name = 'user'
class CustomUserAdmin(UserAdmin):
inlines = (ProfileInline, )
list_select_related = ( 'profile', )
list_display = ('email', 'username', 'first_name', 'last_name', 'is_staff')
fieldsets = (
('Personal information', {'fields': ('first_name', 'last_name', 'username', 'email', 'password')}),
('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
('Important dates', {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
('None', {
'classes': ('wide',),
'fields': ('username', 'email', 'password1', 'password2')}
),
)
def get_inline_instances(self, request, obj=None):
if not obj:
return list()
return super(CustomUserAdmin, self).get_inline_instances(request, obj)
def get_ordering(self, request):
return ['-date_joined']
def save_model(self, request, obj, form, change):
super(CustomUserAdmin, self).save_model(request, obj, form, change)
obj.user = request.user
obj.profile.email_confirmed = True
obj.profile.save()
print(obj)
if not change:
current_site = get_current_site(request)
subject = 'Your Account Login Details'
message = render_to_string('accounts/email/account_detail_email.html', {
'user': obj.user,
'domain': current_site.domain,
})
obj.user.email_user(subject, message)
电子邮件标题
MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
Subject: Your Account Login Details
From: ****@gmail.com
To: admin@admin.com
Date: Wed, 23 Aug 2017 11:21:41 -0000
Message-ID: <20170823112141.16912.15261@DESKTOP-BRG5003>
电子邮件应该转到用户电子邮件而不是管理员,电子邮件应该是管理员电子邮件。
当我打印obj时,它显示了创建的用户的用户名。
感谢任何帮助或建议。提前谢谢。
答案 0 :(得分:0)
需要
obj.email_user(subject, message)
不是
obj.user.email_user(subject, message)
如果还有其他更好的方法,请建议:)
答案 1 :(得分:0)
您可以使用Django自定义管理操作:https://docs.djangoproject.com/en/1.11/ref/contrib/admin/actions/
您的管理类可能如下所示:
def send_account_details(modeladmin, request, queryset):
# Your email sending code here.
# The queryset contains selected users
...
class CustomUserAdmin(UserAdmin):
...
actions = [send_account_details]