簡體   English   中英

我如何使用文件中的 json 對象(例如 text.json)讓我的電子郵件模板在 Django 中讀取

[英]How I can use json object from file (e.g text.json) for my email template to read from in Django

我正在使用 Django 向用戶發送電子郵件模板。 我想將 HTMl 模板中顯示的所有文本存儲在 json 對象中,並在 html 電子郵件模板中將文本作為變量(雙 {{}})引用

-------> util.py

def send_reset_password_email(user: User):
    reset_token = create_user_reset_password_token(user)
    reset_password_url = '{}/account/password/reset/{}'.format(settings.CLIENT_URL, reset_token)
    params = {
        'reset_password_url': reset_password_url,
        'textdata':   ### how I can reference my json file here
    }
    send_template_email(user.email, 'Reset Password','reset_password.html', params)

------->text.json file
{
  "forget_password_email_template": {
    "title": "This is title",
    "sub_title": "This is Sub title",
    "support": "This is title",
    "help_message": "This is help message"
  },
  "confirmation_email_template": {
    "title": "This is title",
    "sub_title": "This is Sub title",
    "support": "This is title",
    "help_message": "This is help message"
  }
}
-------> reset_password.html
<html>
.......
 <p style="margin: 0;" class="forget-password-text">
Forgot your password? Let’s get you a new one! {{params.textdata}}</p><br>
.....
<<html/>

我試過import json但沒有用。 謝謝,如果有其他更好的方法來實現這一點?

我通過將file.json定位在manage.py的同一級別解決了這個問題。 見下面的截圖! 接着

import json
 
with open('emails_text.json') as json_file:
    data = json.load(json_file)

    params = {
        'reset_password_url': reset_password_url,
        'textdata': data,
    }

在此處輸入圖像描述

看來您走在正確的道路上。 這應該可以解決問題:

import json
 
with open('text.json') as json_file:
    data = json.load(json_file)

    params = {
        'reset_password_url': reset_password_url,
        'textdata': data,
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM