2

我想知道是否有任何方法可以将 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))
4

2 回答 2

2

存储消息不需要 RequestContext,它只是显示它。您的代码以什么方式不起作用?您的消息应添加到数据库中,并可在重定向后显示。

于 2011-07-20T16:25:47.130 回答
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
于 2011-11-03T13:50:14.403 回答