【问题标题】:Django redirect to index view with correct URL after form submission表单提交后,Django 重定向到具有正确 URL 的索引视图
【发布时间】:2016-04-30 21:49:47
【问题描述】:

我正在学习 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>

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

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

我尝试过切换

return index(request)

到:

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

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

【问题讨论】:

    标签: python django


    【解决方案1】:

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

    return HttpResponseRedirect("/participants/")
    

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

    另一种解决方案是使用reverse

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

    【讨论】:

      猜你喜欢
      • 2019-01-19
      • 2015-10-11
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 2011-07-08
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多