如何在Django数据库字段中存储变量



我一直在试图弄清楚是否可以将变量存储在Django数据库字段中。这里有一个例子:

class Message(models.Model):
message = models.TextField()

然后在HTML表单字段中,有人输入如下内容:

Hi {{ user.first_name }}, thanks for signing up to our {{ company.name }} newsletter.

然后将其保存到数据库中,当电子邮件发出时,这些字段会自动填充适当的数据。

希望这是有道理的。谢谢

这是类型的解决方案,它不将变量存储在模型中
但是您可以使用模板引擎呈现纯字符串您需要以某种方式填充上下文/传递用户对象+公司-因此这是的中途解决方案

from django.template import Template, Context
from django.core.mail import send_mail
# Fetch Message Obj
msgObj = Message.objects.all().first()
print(msgObj.message) 
# Hi {{ user.first_name }}, thanks for signing up to our {{ company.name }} newsletter.
# I added a user field to message, just for ease in this example
print(msgObj.user) 

# Set msg Contents as a Template
emailtemplate = Template(msgObj.message)
# The hard part, set the context. 
data = {
'user': msgObj.user,
}
if 'company' in msgObj.message: # If, so we're not fetching data that's not needed (a regex like ~ '{{ keywork.[a-zA-Z0-8]+ }}' would be better)
# company in message, get user's company
data['company'] = msgObj.user.company_set.first()
# Use Template Engine to Render with Context
emailtext = emailtemplate.render(Context(data))
print(emailtext)
# Hi Neal, thanks for signing up to our TestCompany newsletter.
send_mail(
'Test Message',         # subject
emailtext,              # contents
None,                   # from
['test@example.com'],   # to
fail_silently=False,
)

根据上下文:您可以使用:

  • 常用关键字或对象的硬编码组合
  • 使用消息Obj中的额外字段来获取其他数据(如公司(
  • 您可以在发送邮件时(像用户一样(将上下文传递给函数

希望您能发现其中的一些有用之处。调查、测试和学习都很有趣。Ty回答问题!

这是models.JSONfield的一个明显用途。存储/检索/更新

instance.variables = { variable1_name: variable_1 value, ... }

你可以用填写一个模板,比如"hello {first_name}"

try:
template.format( **instance.variables )
except KeyError as e:
# one or more {var} in the template string didn't have a definition 
# in instance.variables
print( e.args ) # is a tuple of these undefined key names.

最新更新