2016-04-13 3 views
0

私は1通の電子メールにメッセージとしてhtmlを使用して、このようないくつかの変数を渡す:使用変数()

subject = 'Some Subject' 
plain = render_to_string('templates/email/message.txt',{'name':variableWithSomeValue,'email':otherVariable}) 
html = render_to_string('templates/email/message.html',{'name':variableWithSomeValue,'email':otherVariable}) 
from_email = setting.EMAIL_HOST_USER 
send_email(subject, plain, from_email, [variableToEmail], fail_silently=False, html_message=html) 

良い作品が、今、私は、データベースから一つのテーブルからのメッセージの内容を取る必要があり、表には3つの列があり、最初のレジスタには各列にこの値があります。列subjectAccount Info、列plainHello {{name}}. Now you can access to the site using this email address {{email}}.、列html<p>Hello <strong>{{name}}</strong>.</p> <p>Now you can access to the site using this email address <strong>email</strong>.</p>を有する。

subject = obj.subject 
plain = (obj.plain,{'name':variableWithSomeValue,'email':otherVariable}) 
html = (obj.html,{'name':variableWithSomeValue,'email':otherVariable}) 
from_email = setting.EMAIL_HOST_USER 
send_email(subject, plain, from_email, [variableToEmail], fail_silently=False, html_message=html) 

しかし、これは私にエラーを与える

AttributeError: 'tuple' object has no attribute 'encode'

ので、私は値のため.encode(´utf-8´)を渡ししようとしたと与える:だから私はこのobj = ModelTable.objects.get(id=1)が、その後これを行うデータベースから値を取る

私は同じエラー、その後、各変数の値を変更し、問題がplain = (obj.plain,{'name':variableWithSomeValue,'email':otherVariable})html = (obj.html,{'name':variableWithSomeValue,'email':otherVariable})から来るので、私は間違った方法で変数を渡すと思いますので、どのようにn私は正しい方法でそれをしますか?またはおそらくデータベースのエンコーディングですが、私は.encode(utf-8)を使用すると問題を解決できるはずですが、私は実際に変数nameemailを間違った方法で渡したと思います。

長いポストと私の悪い文法には申し訳ありませんが、もっと必要な情報があれば教えてください。

答えて

1

私はobj.plainとobj.htmlが(データベースに格納されている)テンプレートを表す文字列であると仮定していますか?

この場合、メールのコンテンツをレンダリングする必要があります。しかし、render_to_stringの代わりに、最初の引数にテンプレートパスを指定すると、文字列に基づいてテンプレートを作成し、そのテンプレートをレンダリングする必要があります。

... 
from django.template import Context, Template 
plain_template = Template(obj.plain) 
context = Context({'name':variableWithSomeValue,'email':otherVariable}) 
email_context = plain_template.render(context) 
... 
send_email(...) 

ここでは、レンダリングテンプレートファイルとは対照的にレンダリング文字列テンプレートについて詳しく説明しています。

https://docs.djangoproject.com/en/1.7/ref/templates/api/#rendering-a-context

+0

ありがとう、これは完璧に機能します –