【发布时间】:2011-10-09 13:05:36
【问题描述】:
我想知道是否有任何方法可以将 RequestContext 包含在 django 重定向函数或任何其他上下文中。
问题是我需要在创建对象后添加一条消息,但消息框架需要一个 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))
【问题讨论】:
-
当您在进入视图时立即设置消息然后点击刷新几次会发生什么?
-
我没试过,但是ir解决了新的,问题是下一个视图(显示空间索引的那个)
标签: django redirect django-views django-context