Home > OS >  How to store variables in Django database field?
How to store variables in Django database field?

Time:10-19

I've been trying to figure out if it's possible to store a variable in a Django database field. Here is an example:

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

And then in the HTML form field, someone inputs something like this:

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

That then gets saved to the database, and when an email goes out, those fields are automatically populated with the appropriate data.

Hope this makes sense. Thanks.

CodePudding user response:

This is sort of a solution, it's not storing the variable in the Model..
But you can render plain strings with the template engine.. but you need to somehow fill the context / pass the user object company - so this is halfway solution

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
    ['[email protected]'],   # to
    fail_silently=False,
)

Per the context: You can use:

  • A combination of hardcoded commonly used keywords or Objects
  • Use extra fields in the message Obj to fetch other data (like company)
  • You could pass the context to the function when the mail is being sent (like the user)

Hopefully you find some of this useful. It was interesting to look into, test and learn. Ty for the question!

CodePudding user response:

It's an obvious use for a models.JSONfield. Store/ retrieve/ update

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

and you can fill out a template such as "hello {first_name}" with

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.
  • Related