0

Some fields of the instance does not show up in my email template. See below, the field user_phone is not displayed.

I have view which get or create User:

views.py

    # Get informations for creating the User
    user, created = User.objects.get_or_create(
        username=username,
        email=email,
        first_name=first_name,
        last_name=last_name,
    )
    if created:
        user.groups.add(Group.objects.get(name='Clients'))
        user.profile.phone = telephone
        user.save()
    else:
        user.profile.phone = telephone
        user.save()

I send an email to new user with there infos

models.py

@receiver(post_save, sender=User)
def password_mail(sender, instance, **kwargs):
    if kwargs['created']:
        user_email = instance.email
        first_name = instance.first_name
        user_phone = instance.profile.phone

        subject, from_email, to = 'New account', 'mail@example.com', user_email

        text_content = render_to_string('accounts/mail_welcome.txt', {'first_name': first_name, 'user_phone': user_phone})
        html_content = render_to_string('accounts/mail_welcome.html', {'first_name': first_name, 'user_phone': user_phone})

        # create the email, and attach the HTML version as well.
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.attach_alternative(html_content, "text/html")
        msg.send()

And finally, this the email template:

mail_welcome.txt

{% autoescape off %}
Hello {{ first_name }},

Here is you phone number : {{ user_phone }}

{% endautoescape %}

All the tags are displayed well except the user_phone. Is this because the way this field is saved in my view?

Help appreciated :)

Aurélien
  • 1,617
  • 1
  • 21
  • 33

0 Answers0