How can I use a non-standard object as a state variable? #470
Replies: 2 comments 1 reply
-
I think you need to define a custom vars Bot: |
Beta Was this translation helpful? Give feedback.
-
Okay, here's the answer: 1. Create a custom var using either pc.Model or pc.Base class Bot(pc.Model, table=True):
slug: str
name: str
personality: str
sample: str 2. Within your state class, create an instance of the custom var class and be sure to instantiate it class State(pc.State):
current_bot: Bot = Bot(
slug="",
name="",
personality="",
sample="",
) 3. Create a function to populate the variable on page load def get_bot(self):
with pc.session() as session:
slug = self.get_query_params().get("sl", "Missing slug.")
bot: Bot = session.execute(Bot.select.filter(Bot.slug == slug)).first()
if bot:
self.current_bot = bot[0] 4. Add the function to your definition for the page app.add_page(bot, route="/bot/[sl]", on_load=State.get_bot) 5. Use the variable within your page pc.heading(State.current_bot.sample) WARNING: If you have an attribute called "name," it will not work. If you use this you will instead just get the name of the variable, e.g. "current_bot" in this case. I'm not sure if there's a way around this apart from just not using that attribute name, which is unfortunate. |
Beta Was this translation helpful? Give feedback.
-
I'm not sure if that question makes sense, but here's what's up:
1. Add a page with an on_load event to load data on page load
2—works: Get the associated object and set string variables with its values
2—doesn't work: Get the associated object and set a single object variable
If I do this, then I'll get an error if I try to access bot values like
bot.personality
, saying that these attributes don't exist.What am I doing wrong?
Beta Was this translation helpful? Give feedback.
All reactions