1

我正在建立一个将主题与问题联系起来的网站。每个问题都与一个主题相关联,每个问题都与一个问题相关联,等等。在主页上,我单击一个主题,它会将我带到一个基于 topic_id 的动态 URL。

url(r'^(?P<topic_id>\d+)/$', 'questions'),

当我添加问题时,jQuery 灯箱会在弹出窗口中呈现此 URL

url(r'^(?P<topic_id>\d+)/add_question/$', 'add_question'),

一旦我提交了问题,它就会通过 add_question.html

#add_question.html    
<div class="questionPopupForm">
    <h5><div class="questionPopupTitle"> Add Question</div></h5>
    <form action = "/home/{{ form.topic.id }}/add_question/" method = "post">{% csrf_token %}
        <p>{{ form.as_p }}</p>
        <p><div class="addQuestionButton"><input type = "submit" value = "Ask Question"     class="btn btn-success" /></div></p>
        <input type = "hidden" name = "next" value = "{{ next|escape }}" />
    </form>
</div>

一旦我提交,Action 会将我带到 /home/{{ form.topic.id }}/add_question,这是上面的 URL,链接到 add_question 视图。

#views.py
def add_question(request, topic_id):
    if request.method == "POST":
        form = QuestionForm(request.POST, request.FILES)
        if form.is_valid():
            question = form.save(user = request.user)
            question.topic = Topic.objects.get(pk = topic_id)
            question.save()
            return HttpResponseRedirect("/home/")
    else:
        form = QuestionForm()
        form.q_author = request.user
        form.movie = Topic.objects.get(pk = topic_id)
    return render_to_response("qanda/add_question.html", {'form': form}, context_instance = RequestContext(request))

现在,它带我回家,返回 HttpResponeRedirect('/home/')。我想做的是将用户重定向回同一页面,但是 URL (/{{ topic.id }}/) 中有一个变量,但是 HttpResponseRedirect 不允许我将变量放入其中。我如何回到同一页面?

4

3 回答 3

2

HttpResponseRedirect 需要一个字符串(在本例中为 URL),但您可以即时构建它。例如:

return HttpResponseRedirect("/%s/" % topic.id)
于 2012-11-02T22:21:07.657 回答
2

是的,您可以将变量放入HttpResponseRedirect, 但作为字符串,如下所示:

return HttpResponseRedirect("/%s/" % topic_id)

另外,尝试使用反向使用 url 别名:

return HttpResponseRedirect(reverse('questions', topic_id=topic_id))

或 Django 快捷方式redirect()

from django.shortcuts import redirect
return redirect('questions', topic_id=topic_id)
于 2012-11-02T22:22:16.183 回答
1

你能试试这个吗?

#views.py
def add_question(request, topic_id):
    if request.method == "POST":
        form = QuestionForm(request.POST, request.FILES)
        if form.is_valid():
            question = form.save(user = request.user)
            question.topic = Topic.objects.get(pk = topic_id)
            question.save()
            url = "/home/%s"%(str(topic_id))
            return HttpResponseRedirect(url)
    else:
        form = QuestionForm()
        form.q_author = request.user
        form.movie = Topic.objects.get(pk = topic_id)
    return render_to_response("qanda/add_question.html", {'form': form}, context_instance = RequestContext(request))
于 2012-11-02T22:25:38.740 回答