我想在我的基本模板中添加一个随机标语。我意识到这样做的简单方法是使用我的标语制作一个db表,随机获取,然后将其传递给模板。
问题是,如何在不使用数据库的情况下执行此操作?在我的基本模板中,我想要包含一个带有一堆标语的文件,每行一个,并让模板随机选择一个。我知道random
过滤器会从列表中选择一个随机值,所以不知何故,我需要include
标语文件,但是作为列表。
答案 0 :(得分:0)
我看到两个选项:
1)使用上下文处理器加载此随机引用(即从平面文件中),然后插入上下文。例如:
# create your own context-processor file (myutils/context_processors.py)
def my_random_quote_processor(request):
context = {}
# generate your string you want in template
# ....
context['RANDOM_QUOTE'] = my_random_quote
return context
# in settings.py, tell django to include your processor
TEMPLATE_CONTEXT_PROCESSORS = (
# ...,
'myutils.context_processors.my_random_quote_processor'
)
# in your base template, just include the template var
<p>quote: {{ RANDOM_QUOTE }}</p>
# make sure in your views, you set the context_instance
def my_view(request):
# ...
return render_to_response('myapp/mytemplate.html', c,
context_instance=RequestContext(request))
2)创建一个自定义模板标记,从平面文件中加载引号等:http://docs.djangoproject.com/en/dev/howto/custom-template-tags/
答案 1 :(得分:0)
我会投票给模板标签。将随机引用存储在一个文本文件中,每个引号都在一个单独的行中。然后在模板标签中随机读取一行,这里有一个很好的解释: http://www.regexprn.com/2008/11/read-random-line-in-large-file-in.html。 转载如下:
import os,random filename="averylargefile" file = open(filename,'r') #Get the total file size file_size = os.stat(filename)[6] while 1: #Seek to a place in the file which is a random distance away #Mod by file size so that it wraps around to the beginning file.seek((file.tell()+random.randint(0,file_size-1))%file_size) #dont use the first readline since it may fall in the middle of a line file.readline() #this will return the next (complete) line from the file line = file.readline() #here is your random line in the file print line
最后返回该行,以便您的模板标签可以将其打印出来。
答案 2 :(得分:0)
如果你的口号很小,你可以使用泡菜模块。 并像普通列表一样操作你的基地。 http://docs.python.org/library/pickle.html
但我认为最好的解决方案是将您的标语数据库保存在真正的数据库中
答案 3 :(得分:0)
刚刚找到这个代码段:http://djangosnippets.org/snippets/2121/ 会解决它。