表单提交后,Django重定向到索引视图,并使用正确的URL

Won*_*eve 1 python django

我正在学习Django并且正在尝试创建一个表单,我可以将参与者的信息提交给数据库.

我有一个索引视图,列出所有参与者:

http://127.0.0.1:8000/participants/

单击索引上的按钮将转到表单提交:

http://127.0.0.1:8000/participants/add_participant/

提交表单后,页面返回到索引视图,但URL不正确,它停留在http://127.0.0.1:8000/participants/add_participant/

如果我立即刷新浏览器,它将向数据库添加另一条记录.

add_participant.html

<!DOCTYPE html>
<html>
    <head>
        <title>This is the title</title>
    </head>

    <body>
        <h1>Add a Participant</h1>

        <form id="participant_form" method="post" action="/participants/add_participant/">

            {% csrf_token %}
            {{ form.as_p }}

            <input type="submit" name="submit" value="Create Participant" />
        </form>
    </body>

</html>
Run Code Online (Sandbox Code Playgroud)

views.py

from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect

from participants.models import Participant
from .forms import ParticipantForm


# Create your views here.
def index(request):
    participant_list = Participant.objects.order_by('-first_name')[:50]
    context = {'participants': participant_list}
    return render(request, 'participants/index.html', context)

def add_participant(request):
    if request.method == 'POST':
        form = ParticipantForm(request.POST)  
        if form.is_valid():
            form.save(commit=True) 
            return index(request)
    else:
        form = ParticipantForm() 


        return render(request, 'participants/add_participant.html', {'form': form})
Run Code Online (Sandbox Code Playgroud)

urls.py

from django.conf.urls import url

from . import views
from .models import Participant

app_name = 'participants'

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'add_participant/$', views.add_participant, name='add_participant'),
]
Run Code Online (Sandbox Code Playgroud)

我试过切换

return index(request)
Run Code Online (Sandbox Code Playgroud)

至:

return HttpResponseRedirect("http://127.0.0.1:8000/participants/")
Run Code Online (Sandbox Code Playgroud)

它解决了这个问题...但我怀疑这是"正确"的方法.解决此问题的正确方法是什么?

ahm*_*med 5

您只能将路径传递给重定向响应:

return HttpResponseRedirect("/participants/")
Run Code Online (Sandbox Code Playgroud)

这样,如果您更改域名,重定向将起作用.

另一种解决方案是使用 reverse

from django.core.urlresolvers import reverse
# ...
return HttpResponseRedirect(reverse(index))
Run Code Online (Sandbox Code Playgroud)