2010-01-12 3 views
7

우리 모두 알고있는 (또는해야한다)는, 당신은 이메일 몸 렌더링하는 장고의 템플릿 시스템을 사용할 수 있습니다으로 :이메일 템플릿

def email(email, subject, template, context): 
    from django.core.mail import send_mail 
    from django.template import loader, Context 

    send_mail(subject, loader.get_template(template).render(Context(context)), '[email protected]', [email,]) 

이 내 마음에 하나의 결함이 있습니다의 제목과 내용을 편집하기를 이메일을 보내려면보기와 템플릿을 모두 편집해야합니다. 관리자 사용자에게 템플릿에 대한 액세스 권한을 부여하는 것은 정당 할 수 있지만 원시 파이썬에 대한 액세스 권한을 부여하지는 않습니다.

당신이 이메일에 블록을 지정하고 이메일 보낼 때 개별적으로 당겨 수 있다면 정말 멋질 것입니다 무엇 :

{% block subject %}This is my subject{% endblock %} 
{% block plaintext %}My body{% endblock%} 
{% block html %}My HTML body{% endblock%} 

하지만 당신은 어떻게 할 것입니까? 한 번에 한 블록 만 렌더링하는 방법에 대해 어떻게 생각하십니까?

답변

11

이것은 세 번째 반복 작업입니다.

{% block subject %}{% endblock %} 
{% block plain %}{% endblock %} 
{% block html %}{% endblock %} 

나는 기본적으로 목록을 통해 보내는 이메일을 반복하는 리팩토링 한 단일 및 다중 유틸리티 하나의 이메일로 전송하는 방법과 django.contrib.authUser의가 (이 있습니다 : 그것은 당신이 이메일 템플릿과 같이 있다고 가정). 나는 내가 분별있게 필요로하는 것보다 아마도 더 많이 다루고있다. 그러나 너는 거기에 간다.

필자도 파이썬을 통해 맨 위로 떠났을지도 모른다.

def email_list(to_list, template_path, context_dict): 
    from django.core.mail import send_mail 
    from django.template import loader, Context 

    nodes = dict((n.name, n) for n in loader.get_template(template_path).nodelist if n.__class__.__name__ == 'BlockNode') 
    con = Context(context_dict) 
    r = lambda n: nodes[n].render(con) 

    for address in to_list: 
     send_mail(r('subject'), r('plain'), '[email protected]', [address,]) 

def email(to, template_path, context_dict): 
    return email_list([to,], template_path, context_dict) 

def email_user(user, template_path, context_dict): 
    return email_list([user.email,], template_path, context_dict) 

def email_users(user_list, template_path, context_dict): 
    return email_list([user.email for user in user_list], template_path, context_dict) 

언제든지 개선 할 수 있다면 그렇게하십시오.

+0

음 & * $ # 나를 탈출 텍스트를 방지하기 위해 autoescape을 해제 발견했다. 그것은 작동합니다. from/from-name/reply-to 설정을 허용하기 위해 기본에 더 많은 필드를 추가하는 것을 고려하십시오. – Oli

+0

하, 나는 PITA 인 세 가지 템플릿으로이 작업을 해왔다. 나에게서 명확한 +1! –

+0

나는 그것을 좋아한다. 난 항상 잘 작동하는 별도의 템플릿을 사용했지만 이것은 다루기에 훨씬 더 좋았다. (특히 어쨌든 모든 템플릿에 대해 동일한 컨텍스트를 원하기 때문에). –

0

몸체 용과 대상 용 템플릿 두 개를 사용하면됩니다.

{% extends "base.txt" %} 

{% if subject %}Subject{% endif %} 
{% if body %}Email body{% endif %} 
{% if html %}<p>HTML body</p>{% endif %} 

이제 우리는 템플릿을 세 번 렌더링해야하지만, 상속이 제대로 작동 : 나는 템플릿 상속이 {% body %} 태그를 사용하여 작업 할 수 없었다

+0

두 개의 파일은 본질적으로 동일한 것을 위해 두 개의 파일 이름을 의미합니다. 그것은 그 많은 템플릿들 위에 계속 머물러 야하는 것에서의 고통입니다. – Oli

0

, 그래서 나는이 같은 템플릿으로 전환.

c = Context(context, autoescape = False) 
subject = render_to_string(template_name, {'subject': True}, c).strip() 
body = render_to_string(template_name, {'body': True}, c).strip() 
c = Context(context, autoescape = True) 
html = render_to_string(template_name, {'html': True}, c).strip() 

는 또한 비 HTML 텍스트를 렌더링 할 때 필요한 이메일