其他分享
首页 > 其他分享> > Django 重新配置User表在admin中的显示

Django 重新配置User表在admin中的显示

作者:互联网

需求

接上一篇配置邮件发送功能,这里对平台的用户发送邮件。
发送邮件的一些必备因素:

具体实现:

from django.contrib.auth.models import User

class UserConfig(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE,verbose_name="用户")
    receive = models.BooleanField(default=False, verbose_name="是否开启邮件接收")

    class Meta:
        verbose_name_plural = verbose_name = '账户配置'

    def __str__(self):
        if self.receive:
            return "接收邮件通知"
        else:
            return "不接收邮件通知"
# 先将新表以StackedInline的方式进行继承
class UserConfigInline(admin.StackedInline):
    model = models.UserConfig

admin.site.unregister(User)
@admin.register(User)
class CustomUserAdmin(UserAdmin):
    list_display = ["id","username","email","is_superuser","is_active","last_login","userconfig"]
    list_display_links = ["username"]
    inlines = [UserConfigInline]

此时的后台页面显示效果为:
image
image

from django.core.mail import send_mail

class CheckEmail(LoginRequiredMixin,View):
    def get(self,request):
        email = request.user.email
        if email:
            try:
                send_mail("这是一封测试邮件", "测试发送邮件", settings.EMAIL_HOST_USER, [email])
            except:
                print("邮件发送失败")
        else:
            messages.success(request, "请配置你的邮箱/输入一个正确的邮箱地址")
            return redirect("phone:import")
        messages.success(request, "邮件已发送")
        return redirect("phone:import")
from django.contrib.auth.models import User

def send_email_msg():
    user_list = User.objects.filter(userconfig__receive=True,is_superuser=True)
    target_email = [user.email for user in user_list if user.email]
    if target_email:
        try:
            send_mail("导入任务进度通知","当前任务处理:已完成","sender@qq.com",target_email)
        except:
            print("邮件发送失败")
            return
    return

标签:admin,Django,发送,models,表在,User,email,邮件,user
来源: https://www.cnblogs.com/lisicn/p/15439140.html