简体   繁体   English

在模型中访问视图数据

[英]Accessing View Data In Model

Is there a way to access a variable within charfield entries. 有没有一种方法可以访问charfield条目中的变量。 Lets say in my views I have... 让我说我有...

first_name = "John"
last_name = "Smith"

In my model I have a list of set greetings, lets say about 20 of them, which I want to randomly pick one and within that entry I want to be able to refer to these variables. 在我的模型中,我有一组问候语列表,可以说约20个,我想随机选择一个,在该条目中我希望能够引用这些变量。

My charfield entries in my models will be something like... 我在模型中的charfield条目将类似于...

Welcome {{first_name}} Im glad you could come back Mr.{{last_name}}
Hello {{first_name}} {{last_name}} welcome back
Hey there {{last_name}}!
etc...  

So when I want to display one of those entries from my model, it will fill in the first_name,last_name fields from the data's view... 因此,当我要显示模型中的条目之一时,它将在数据视图中填充first_name,last_name字段...

I did try it with template tags but it just gets printed out as a string which I expected it to do so. 我确实尝试过使用模板标签,但是它只是作为我期望的字符串打印出来。 I understand this may be confusing. 我了解这可能会造成混淆。

Or is the best way to just code something that finds the {{first_name}} and replaces it with that value... 或只是编码找到{{first_name}}并将其替换为该值的东西的最好方法...

Create string like 创建像这样的字符串

"Welcome {first_name} Im glad you could come back Mr.{last_name}"

Then in view(using python string formatting) 然后在视图中(使用python字符串格式)

Model.field.value.format(first_name=first_name,last_name=last_name")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM