Search code examples
pythondjangotemplatesf-string

Python/Django f-strings interpreting a string as input


Running out of ideas where to look.

I am trying to set up a string that can be edited outside my code and stored by the user and have that string feed into an f-string inside my code.

Example: Take the following value that is stored in database CharField: Hello {user}! How are you? I want to grab that and feed it into Python to treat as the content of an f-string such that:

>>> user = 'Bob'
>>> stringFromOutside = 'Hello {user}! How are you?'
>>> print(f'{stringFromOutside}')
Hello {user}! How are you?

prints "Hello Bob! How are you?"

I oversimplified for the example, because that's the core of where I'm lost.

  • I have tried nesting the {stringFromOutside} in a second f-string, but that doesn't work.
  • I have also tried double {{user}} inside the template file, but that did not work.

Use Case in case I'm just being obtuse and doing the whole thing wrong
I have an application that I want to expose to the administrator the ability to write templates and save them in the database. The templates need to be able to pull from several different objects and all the properties of those objects, so it would be very cumbersome to try to add the substitutions manually for each possible variable that the template can include.


Solution

  • I don't think you can use the f-string here, but, I would rather choose str.format(...)

    In [3]: user = 'Bob'
    
    In [4]: str_template = 'Hello {user}! How are you?'
    
    In [5]: variables = {"user":user}
    
    In [6]: str_generated = str_template.format(**variables)
    
    In [7]: str_generated
    Out[7]: 'Hello Bob! How are you?'