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


    需求

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

    • 必须是管理员
    • 必须填写了邮箱
    • 用户可以修改是否接收邮件通知:必须为开启状态
    • 开启一个发送测试邮件的功能

    具体实现:

    • 创建一个用户配置表,存储是否接收邮件通知的设置。models.py
    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 "不接收邮件通知"
    
    • 配置admin.py 将新表通过inline(内联)的方式添加到用户表的字段
    # 先将新表以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

    • 增加发送测试邮件的功能
      • views.py:
    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")
    
    • 主要业务的发送邮件通知部分 task.py
    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
    
  • 相关阅读:
    tcprstat分析服务的响应速度
    mysqldump之不老将
    Java数据持久层框架 MyBatis之API学习二(入门)
    Java数据持久层框架 MyBatis之API学习一(简介)
    插入数据库日期格式转换
    eclipse出现错误:he type java.util.Map$Entry cannot be resolved. It is indirectly referenced
    注释中不允许出现字符串 "--"。
    mybatis if条件查询 及<号的问题
    This is probably because there is no OLE editor registered against the type of file you were trying to open.
    github not authorized eclipse
  • 原文地址:https://www.cnblogs.com/lisicn/p/15439140.html
Copyright © 2020-2023  润新知