Skip to main content
 首页 » 编程设计

python之提交表单后,Django 使用正确的 URL 重定向到索引 View

2025年05月04日50lyj

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

我有一个索引 View ,其中列出了所有参与者:

http://127.0.0.1:8000/participants/

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

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

提交表单后,页面回到索引 View ,但是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> 

View .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}) 

网址.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'), 
] 

我试过切换

return index(request) 

到:

return HttpResponseRedirect("http://127.0.0.1:8000/participants/") 

它解决了问题...但我怀疑这是“正确”的做法。解决此问题的正确方法是什么?

请您参考如下方法:

您可以只传递重定向响应的路径:

return HttpResponseRedirect("/participants/") 

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

另一个解决方案是使用reverse

from django.core.urlresolvers import reverse 
# ... 
return HttpResponseRedirect(reverse(index))