【问题标题】:Using a User uploaded file as an email template in django在 django 中使用用户上传的文件作为电子邮件模板
【发布时间】:2017-10-23 14:10:30
【问题描述】:

我在 Django 模型中有以下 Python 代码,用于向模型的“所有者”发送电子邮件。我希望管理员能够上传将要使用的文件(如果已上传),或者如果尚未加载则将使用默认模板文件。这是代码:

def send_invitation(self):
    '''
    sends an invitation from admin to accept a listing
    '''

    try:
        if self.user or not self.email : return False
    except :
        try: email_body_template = Parameter.objects.get(name='send_invitation_email.txt').f
        except: email_body_template = 'listing_cms_integration/email/send_invitation_email.txt'
        try: email_subject_template = Parameter.objects.get(name='send_invitation_email_subject.txt').f
        except: email_subject_template = 'listing_cms_integration/email/send_invitation_email_subject.txt'

        context = Context()
        context['listing'] = self
        context['site'] = Site.objects.get_current().domain

        subject = render_to_string(email_subject_template, context)
        message = render_to_string(email_body_template, context)

        email = EmailMessage(subject, message, to=[self.email])
        email.send()

        return True

如果我没有名为“send_invitation_email.txt”的参数,那么它可以正常工作。按指定选择参数时,出现以下错误。

强制转换为 Unicode:需要字符串或缓冲区,找到 FieldFile

如何将用户上传的文件转换为可用作电子邮件模板的文件?

编辑

添加参数模型

class Parameter (models.Model):
    name = models.CharField(
        verbose_name = 'Title',
        max_length = 255,
        unique=True,
    )
    description = models.TextField()
    f = models.FileField (
        verbose_name = 'Input File',
        help_text = "Email body template"
    )

【问题讨论】:

  • 请出示您的Parameter模特

标签: python django


【解决方案1】:

您已经发送到 render_to_string() 函数文件实例而不是字符串。 试试看:

email_body_template = Parameter.objects.get(name='send_invitation_email.txt').f.read()

【讨论】:

  • 生成错误TemplateDoesNotExist at /admin/listing_cms_integration/listing/然后显示文件内容
  • 另外,当使用email_body_template = 'listing_cms_integration/email/send_invitation_email.txt' 时正在发送要渲染的文件
【解决方案2】:

我就是这样做的。

我将MEDIA_ROOT 添加到我的TEMPLATES DIRS

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            ...
            os.path.join(MEDIA_ROOT),
            ],
        'OPTIONS': {

我改变了函数来获取文件名

email_body_template = Parameter.objects.get(name='send_invitation_email.txt').f.name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-12
    • 2012-02-18
    • 2019-07-18
    • 2015-04-27
    • 2013-07-23
    • 2011-04-02
    • 2011-02-18
    相关资源
    最近更新 更多