Closed tyapkov closed 7 years ago
Есть предложение сделать пример для документации как передавать правильно контекст в сообщении, а также другие переменные и использовать их в шаблоне. Могу это сделать, но для этого мне нужно знать как работать с переменными в шаблоне. Раньше я делал примерно так:
def send_activation_email(self):
context = {'user': self.user,
'without_usernames': False,
'protocol': get_protocol(),
'activation_days': ACCOUNTS_REGISTRATION_ACTIVATION_DAYS,
'activation_key': self.activation_key,
'site': Site.objects.get_current()}
subject = render_to_string('accounts/emails/activation_email_subject.txt', context)
subject = ''.join(subject.splitlines())
message = render_to_string('accounts/emails/activation_email_message.txt', context)
send_mail(subject, message, None, EMAIL_DEFAULT_FROM_EMAIL, [self.user.email])
При этом сам шаблон выглядел так:
{% load i18n %}{% autoescape off %}
{% if not without_usernames %}{% blocktrans with user.username as username %}Dear {{ username }},{% endblocktrans %}
{% endif %}
{% blocktrans with site.name as site %}Thank you for signing up at {{ site }}.{% endblocktrans %}
{% trans "To activate your account you should click on the link below:" %}
{{ protocol }}://{{ site.domain }}{% url 'accounts:activate' activation_key %}
{% trans "Thanks for using our site!" %}
{% trans "Sincerely" %},
{{ site.name }}
{% endautoescape %}
Вопрос у меня сейчас в том, как в шаблоне использовать {% url %} тэги, а также другие переменные? Может быть скините кусочек кода из проекта, чтобы можно было разобраться? Спасибо!
send_db_mail(
'activation_email_message',
{'user': self.user,
'without_usernames': False,
'protocol': get_protocol(),
'activation_days': ACCOUNTS_REGISTRATION_ACTIVATION_DAYS,
'activation_key': self.activation_key,
'site': Site.objects.get_current()}
)
переменные контекста передаются как в subject так и в message. ну и обрабатывается стандартным образом для django: https://github.com/LPgenerator/django-db-mailer/blob/master/dbmail/backends/mail.py#L218
Все увидел и все заработало. Спасибо! Проблема была с шаблоном, а не с db_mailer. Во время тестирования возник другой вопрос, может быть баг, а может нет...При загрузке формы шаблона в админке, все html тэги шаблона сбрасываются. Не сталкивались с такой проблемой?
логично. html вырезается, если не указан тип шаблона html (иначе текст). так же отправляется 2 типа при использовании html. это на случай когда клиент не поддерживает вложения (подробнее в доке джанги). https://github.com/LPgenerator/django-db-mailer/blob/master/dbmail/backends/mail.py#L243
Точно, не заметил этой опции. Во всем разобрался, завтра окончательно прикручу dm_mailer к проекту. Еще раз спасибо за помощь!
np)
Hi guys,
What is the working example of providing arguments to send_db_mail()?
Following example is not working:
because:
SyntaxError: positional argument follows keyword argument
Can you please write me how to pass arguments?
Also I have another question. Is it possible to use tags inside of template? I want to render url in the template with something similar to {% url ... %} Thanks!