Search code examples
pythondjangorender

How to render html text saved inside a field in the database using django?


Good evening!

I created in my model a skeleton for sending personalized e-mails. As code below:

class EmailSituacao(models.Model):
    referencia = models.CharField(blank=False, null=True, unique=True, max_length=255)
    assunto = models.CharField(blank=True, null=True, max_length=255)
    remetente= models.EmailField(blank=True, null=True)
    mensagem = RichTextField(blank=True, null=True)
    def __str__(self):
        return self.referencia+'/'+self.assunto

I put the following code in the "message" field:

<p><span style="color:#e74c3c">Este &eacute; um e-mail autom&aacute;tico. Por favor, n&atilde;o responda este e-mail. Para contato utilize</span></p>


<hr />
<p><strong>DADOS DA INSCRI&Ccedil;&Atilde;O</strong></p>

<p>Curso: {{curso}}</p>

<p>Data do Curso: {{dt_hr_inicio}}&nbsp; - {{dt_hr_fim}}</p>

<hr />
<p><strong>INFORMA&Ccedil;&Otilde;ES</strong></p>

<p>Informamos que voc&ecirc; foi pr&eacute; inscrito para particicipar do curso descrito acima. clique aqui para acessar o Sistema de Curso.</p>

That way I need to render within my view the standard text that comes from the "message" field. I'm trying to do it in the view the same way I do with an html page. Here's the view code:

def emailSgc(id_inscricao):
    inscricao= models.Inscricao.objects.get(pk=id_inscricao)
    context_email={
        'curso':inscricao.Turma.Curso.Curso,
        'dt_hr_inicio':inscricao.Turma.dt_hr_inicio,
        'dt_hr_fim':inscricao.Turma.dt_hr_fim
    }
    if inscricao.situacao == 'P':
        textoBase=EmailSituacao.objects.get(referencia='sgc_pre_inscrito')
        template=get_template(textoBase.mensagem)
        mensagem = template.render(context_email)
    try:
        enviaEmail(textoBase.assunto,textoBase.remetente,inscricao.Aluno.usuario.email,mensagem)
    except:
        pass

But the line

mensagem = template.render(context_email)

is not correct. How do I render a standard text with the context stored inside a field in the bank and send it by email replacing the variables with {{course}}


Solution

  • i found the answer

    just put the following code in the view

    template = Template(textoBase.mensagem)
        context_email = Context({'curso':inscricao.Turma.Curso.Curso,
                                'dt_hr_inicio':inscricao.Turma.dt_hr_inicio,
                                'dt_hr_fim':inscricao.Turma.dt_hr_fim})
        mensagem = template.render(context_email)