我想知道是否有任何方法可以在django重定向函数或任何其他上下文中包含RequestContext。
问题是我需要在创建对象后添加消息,但是framewotk消息需要RequestContext才能工作,或者需要另一个返回消息的上下文。如何返回上下文?
我的观点:
@permission_required('spaces.add_space')
def create_space(request):
"""
Returns a SpaceForm form to fill with data to create a new space. There
is an attached EntityFormset to save the entities related to the space. Only
site administrators are allowed to create spaces.
:attributes: - space_form: empty SpaceForm instance
- entity_forms: empty EntityFormSet
:rtype: Space object, multiple entity objects.
:context: form, entityformset
"""
space_form = SpaceForm(request.POST or None, request.FILES or None)
entity_forms = EntityFormSet(request.POST or None, request.FILES or None,
queryset=Entity.objects.none())
if request.user.is_staff:
if request.method == 'POST':
space_form_uncommited = space_form.save(commit=False)
space_form_uncommited.author = request.user
if space_form.is_valid() and entity_forms.is_valid():
new_space = space_form_uncommited.save()
space = get_object_or_404(Space, name=space_form_uncommited.name)
ef_uncommited = entity_forms.save(commit=False)
for ef in ef_uncommited:
ef.space = space
ef.save()
# We add the created spaces to the user allowed spaces
request.user.profile.spaces.add(space)
# This message does not work since there's no context.
messages.info(request, 'Space %s created successfully.' % space.name)
return redirect('/spaces/' + space.url)
return render_to_response('spaces/space_add.html',
{'form': space_form,
'entityformset': entity_forms},
context_instance=RequestContext(request))
else:
return render_to_response('not_allowed.html',
context_instance=RequestContext(request))
答案 0 :(得分:2)
存储消息不需要RequestContext,它只显示它。你的代码以什么方式工作?您的消息应该添加到数据库中,并且可以在重定向后显示。
答案 1 :(得分:0)
我有同样的问题,只是想澄清它“只是有效”
def first_view(request)
...
messages.info(request, "Some info message")
...
return redirect('second_view')
def second_view(request)
...
return render_to_response('template.html',{},context_instance=RequestContext(request))
-> will correctly display the message