我有一个奇怪的问题,我想使用上下文处理器添加一个全局查询.这就是我通过以下方式做到的:
在我的应用程序中制作了processor.py:
from myproject.myapp.models import Foo
def foos(request):
return {'foos': Foo.objects.all()}
Run Code Online (Sandbox Code Playgroud)
在我的setting.py结束时我添加了这个:
TEMPLATE_CONTEXT_PROCESSORS = ('myapp.processor.foos',)
Run Code Online (Sandbox Code Playgroud)
最后我传递了我的观点:
def index_view(request):
return render_to_response('index.html', {}, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
在我的index.html模板:
<select id="select_foo">
{% for foo in foos %}
<option value="/{{ foo.slug }}">{{ foo.name }}</option>
{% endfor %}
</select>
Run Code Online (Sandbox Code Playgroud)
最后我的网址:
(r'^$', 'myapp.views.index_view'),
Run Code Online (Sandbox Code Playgroud)
我的foos显示没有任何问题,但我的media_url和其他上下文已经消失.可能是什么问题
我需要所有管理模板中的请求对象.在前端模板中,我可以通过以下方式呈现模板来实现RequestContext:
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request)
)
Run Code Online (Sandbox Code Playgroud)
有了它,我可以在前端访问请求对象:
{{ request.path }}
Run Code Online (Sandbox Code Playgroud)
如何在Django 1.2中为所有管理员视图执行此操作?
编辑:
我希望'success_url'(即result.html)显示'form.process()'中的'data'.以下代码显然不起作用.任何人都可以告诉我它有什么问题或建议另一种方法来基本上查看模板中的上下文"数据"(以列表或字典的形式),即在表单形式之后向用户显示数据的更好方法提交.
提前谢谢了.
-- urls.py --
url(r'^$', view='main_view'),
url(r'^result/$', view='result_view'),
-- views.py --
class ResultView(TemplateView):
template_name = "result.html"
class MainView(FormView):
template_name = 'index.html'
form_class = UserInputForm
success_url = 'result/'
def form_valid(self, form):
data = form.process()
return super(MainView, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(MainView, self).get_context_data(**kwargs)
context['data'] = data
return context
main_view = MainView.as_view()
result_view = ResultView.as_view()
Run Code Online (Sandbox Code Playgroud)