You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中如何将views.py的值传递至sendmail模板并显示

问题分析与解决

你遇到的问题核心是:在Form中调用render_to_string渲染邮件模板时,没有传入包含getlogincode的上下文,导致模板无法渲染这个变量,所以邮件里看不到登录码。

Django完全支持把View中的上下文传递到Form里,下面给你两种可行的解决方案:

方案一:Form内部直接获取登录码(更简洁)

既然Form里已经能拿到self.user,可以直接通过用户关联的Profile获取登录码,不需要从View传递。修改forms.py如下:

class MyCustomLoginForm(LoginForm):
    def login(self, *args, **kwargs):
        # 通过当前用户直接获取关联的Profile
        profile = Profile.objects.get(user=self.user)
        getlogincode = profile.login_code
        
        # 渲染模板时传入上下文
        html_content = render_to_string('getlogincode_sendmail.html', {'getlogincode': getlogincode})
        
        send_mail(
            subject="Reliance Assurance Worth",
            message=html_content,
            from_email=settings.EMAIL_HOST_USER,
            recipient_list=[self.user.email],
            html_message=html_content
        )
        
        return super().login(*args, **kwargs)

方案二:从View传递上下文到Form

如果一定要从View传递登录码到Form,需要修改Form的login方法接收上下文参数,同时在View中调用时传入:

1. 修改forms.py

class MyCustomLoginForm(LoginForm):
    # 新增context参数接收View传递的上下文
    def login(self, *args, context=None, **kwargs):
        context = context or {}
        html_content = render_to_string('getlogincode_sendmail.html', context)
        
        send_mail(
            subject="Reliance Assurance Worth",
            message=html_content,
            from_email=settings.EMAIL_HOST_USER,
            recipient_list=[self.user.email],
            html_message=html_content
        )
        
        return super().login(*args, **kwargs)

2. 修改views.py

完善登录请求的处理逻辑,在Form验证通过后传入上下文:

def GetLoginCodeView(request):
    if request.method == 'POST':
        form = MyCustomLoginForm(request, data=request.POST)
        if form.is_valid():
            # 获取当前用户的登录码(优化原循环逻辑)
            profile = Profile.objects.get(user=request.user)
            getlogincode = profile.login_code
            
            # 调用login方法时传入上下文
            form.login(context={'getlogincode': getlogincode})
            
            # 登录成功后跳转(根据你的需求修改)
            return redirect('home')
    else:
        form = MyCustomLoginForm(request)
    
    return render(request, 'your_login_template.html', {'form': form})

额外优化建议

原View中用filter循环获取登录码的逻辑可以简化,因为一个用户通常对应一个Profile,直接用get()获取单个对象更高效,避免不必要的循环。

内容的提问来源于stack exchange,提问作者Oghomwen Ogunmwonyi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 19:32:46