感谢 Simeon 的回答,以及其他一些让我意识到在类的方法self.request.user
内部使用的可能性的 stackoverflow 问题,我能够像这样解决我的问题。 内部:def extra_context(self):
CustomSearchView(SearchView)
views.py
from haystack.views import SearchView
class MySearchView(SearchView):
def extra_context(self):
if self.request.user.is_authenticated:
member = self.request.user.get_profile()
else:
# just fooling the haystack config, since this view is set to localhost
return { 'x' : 0 } # which would be equivalent to a direct_to_template view
# getting member tasks
tasks = list()
for elem in member.task_set.all().filter(completed=False).order_by('priority', 'dueDate')[:5]:
tasks.append(elem)
return { 'tasks': tasks }
在模板中:
<a href="tasks/" style="color: #ffffff">Tasks</a>
<ul id="tasksPane">
{% for task in tasks %}
<li><a href="/tasks/{{ task.id }}" id="tasksP" {% if task.priority == 'c' %} style="color: #99ff44" {% endif %}
{% if task.priority == 'b' %} style="color: #024dac" {% endif %}
{% if task.priority == 'a' %} style="color: #aa0022" {% endif %}
><input type="checkbox" name="task" value="completed">{{ task.task }}</a></li>
{% endfor %}
</ul>
这样,我不需要在模板中执行任何主要逻辑,这正是我所需要的,而且我认为 django 会不赞成这种方法,因为它不允许模板中的filter
andorder_by
方法。
当然,在我的urls.py
:
# haystack
from haystack.forms import ModelSearchForm
from haystack.query import SearchQuerySet
from haystack.views import SearchView, search_view_factory
sqs = SearchQuerySet()
from member.views import MySearchView
urlpatterns = patterns('',
url(r'^$', search_view_factory(
view_class=MySearchView,
template='base.html',
searchqueryset=sqs,
form_class=ModelSearchForm
), name='haystack_search'),
)