Django:表单POST后保留相同的URL

时间:2019-06-07 23:56:26

标签: django

好的,我是Django的初学者,我对表单提交和重定向有一个快速的问题。到目前为止,我一直在遵循指南,并在使用基于函数的视图。

我现在遇到的主要问题是提交表单后,URL从http://127.0.0.1:8000/projects/1/更改为http://127.0.0.1:8000/projects/1/updateReport

在提交表单后,如何使我的URL返回http://127.0.0.1:8000/projects/1/(不带/ updateReport /)。非常感谢您的帮助!

这是我的网址:

url(r'^(?P<project_id>[0-9]+)/$', views.projectView, name='projectView'),
url(r'^(?P<project_id>[0-9]+)/updateReport/$', views.updateReport, name='updateReport')

这是我的观点:

def projectView(request, project_id):
    project = get_object_or_404(Project, id=project_id)
    reportSet = project.report_set.all()
    context = {
        'project': project,
        'reports': reportSet
    }
    return render(request,'projectMgmt/projectView.html',context)

def updateReport(request, project_id):
    project = get_object_or_404(Project, id=project_id)
    sys_msg = "Report Updated!"

    #Increment Report Version
    reportSet = project.report_set.all()
    if reportSet.last():
        version = reportSet.last().reportVersion + 1
    else:
        version = 1 #New Report for project

    #New Report Text (name="reportText" from textarea in page)
    newText=request.POST['reportText']

    try:
        newReport = Report(project=project, reportVersion=version, reportText=newText)
        newReport.save()
    except:
        sys_msg="Error!"

    context = {
        'project': project,
        'reports': reportSet,
        'sys_msg': sys_msg
    }

    return render(request, 'projectMgmt/projectView.html',context)

2 个答案:

答案 0 :(得分:0)

更改此行以将其重定向到您要呈现的url视图:请参见Docs

helm install ./my-app --set tag=242920

对此

return render(request, 'projectMgmt/projectView.html',context)

答案 1 :(得分:0)

from django.shortcuts import redirect
  
      
  1. 通过传递视图名称以及可选的一些位置或关键字参数;该网址将使用   reverse()方法:
  2.   
def updateReport(request, project_id):
    ...
    return redirect('projectView', project_id=1)
  

2。通过传递一个硬编码的URL重定向到:

def updateReport(request, project_id):
    ...
    return redirect('/proects/'+ project_id + '/')