"redirect" django 的功能不起作用,提交表单后,用户仍停留在同一页面上
"redirect" function of django is not working and after submitting the form, user remains on same page
在 views.py 的函数“createProject”中,我希望用户在提交表单后重定向到“项目”页面。
但我不知道我的错误在哪里。提交表单后,它不会将用户重定向到“项目”页面,而是保留在同一页面上。
"views.py" 文件:
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import ProjectForm
from .models import Project
def projects(request):
projects = Project.objects.all()
context = {'projects':projects}
return render(request, 'projects/projects.html', context)
def project(request, pk):
return render(request, 'projects/single-project.html')
def createProject(request):
form = ProjectForm()
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
form.save()
redirect('projects')
context = {'form':form}
return render(request, 'projects/project_form.html', context)
这里是“urls.py”文件:
from django.urls import path
from . import views
urlpatterns = [
path('', views.projects, name = 'projects'),
path('project/<str:pk>/', views.project, name = 'project'),
path('create-project/', views.createProject, name = 'create-project'),
]
这里是“project-form.html”[我用的是Django“ModelForm”]:
from django.db.models.base import Model
from django.forms import ModelForm
from .models import Project
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = ['title', 'description', 'demo_link', 'source_link', 'tags']
谁能帮我找出这里的错误?
为什么在提交表单后,它没有将其重定向到“项目”页面并保持在同一页面上?
此问题是因为从未返回重定向响应,所以:
if form.is_valid():
form.save()
return redirect('projects')
# ^^^ Add this
在 views.py 的函数“createProject”中,我希望用户在提交表单后重定向到“项目”页面。
但我不知道我的错误在哪里。提交表单后,它不会将用户重定向到“项目”页面,而是保留在同一页面上。
"views.py" 文件:
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import ProjectForm
from .models import Project
def projects(request):
projects = Project.objects.all()
context = {'projects':projects}
return render(request, 'projects/projects.html', context)
def project(request, pk):
return render(request, 'projects/single-project.html')
def createProject(request):
form = ProjectForm()
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
form.save()
redirect('projects')
context = {'form':form}
return render(request, 'projects/project_form.html', context)
这里是“urls.py”文件:
from django.urls import path
from . import views
urlpatterns = [
path('', views.projects, name = 'projects'),
path('project/<str:pk>/', views.project, name = 'project'),
path('create-project/', views.createProject, name = 'create-project'),
]
这里是“project-form.html”[我用的是Django“ModelForm”]:
from django.db.models.base import Model
from django.forms import ModelForm
from .models import Project
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = ['title', 'description', 'demo_link', 'source_link', 'tags']
谁能帮我找出这里的错误? 为什么在提交表单后,它没有将其重定向到“项目”页面并保持在同一页面上?
此问题是因为从未返回重定向响应,所以:
if form.is_valid():
form.save()
return redirect('projects')
# ^^^ Add this