2017-08-23 110 views
0

我想在管理員創建用戶帳戶後向用戶發送電子郵件。從django admin發送帳戶詳細信息給用戶郵箱

賬戶/ 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: [email protected] 
Date: Wed, 23 Aug 2017 11:21:41 -0000 
Message-ID: <[email protected]> 

電子郵件應該到用戶的電子郵件不是管理員和電子郵件應是管理員的電子郵件。

當我打印obj時,它顯示了用戶創建的用戶名。

讚賞任何幫助或建議。提前致謝。

回答

0

它需要

obj.email_user(subject, message) 

obj.user.email_user(subject, message) 

如果有任何其他更好的辦法,那麼請建議:)

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] 
+0

謝謝你給我另一個絕妙的主意。現在不需要有「管理員操作」,但如果需要,可以在將來使用。 –

相關問題