gpt4 book ai didi

python - 用户提交博客文章后重定向到主页?

转载 作者:行者123 更新时间:2023-12-05 01:22:21 24 4
gpt4 key购买 nike

我对使用 Django 和一般编码非常陌生。所以我已经弄清楚如何使表单提交到我的数据库,但现在当它提交时,它只会将您带到空白的 blog_post View ,而我不明白如何正确重定向。

这是views.py:

from django.shortcuts import render, redirect
from .models import post
from django.views import generic, View
from django.views.decorators.http import require_GET
from django.http import HttpResponse, HttpResponseRedirect
from .forms import PostForm

# Views for post list


class postslist(generic.ListView):
model = post
queryset = post.objects.filter(status=1).order_by('-created_on')
template_name = 'home.html'
paginate_by = 4

# view for individual post


class postdetail(generic.DetailView):
model = post
template_name = "post.html"


def blog_post(request):

form = PostForm(request.POST or None)

if request.method == "POST":
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect("blog:success")

context = {'form': form,
}

return render(request, "create_post.html", context)


def success(request):
return HttpResponseRedirect("home.html")

url.py:

from . import views
from django.urls import path, include
from .views import *


urlpatterns = [
# home
path('', views.postslist.as_view(), name='home'),
# add post
path('blog_post/', views.blog_post, name='blog_post'),
# success for blog post
path('success/', views.success, name='success'),
# posts
path('<slug:slug>/', views.postdetail.as_view(), name='post_detail'),
]

我尝试了 httpresponseredirect 和重定向的一些变体,但我就是无法理解它,也无法在网上找到它。

最佳答案

假设您想在由 postslist View 呈现的 home.html 中进行重定向,因此 View 应如下所示:

def blog_post(request):

if request.method == "POST":
form=PostForm(request.POST)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect("blog:home")
else:
form = PostForm()

context = {'form': form,
}

return render(request, "create_post.html", context)

还需要在urls.py中指定app_name='blog':

from . import views
from django.urls import path, include
from .views import *

app_name='blog'

urlpatterns = [
# home
path('', views.postslist.as_view(), name='home'),
# add post
path('blog_post/', views.blog_post, name='blog_post'),
# posts
path('<slug:slug>/', views.postdetail.as_view(), name='post_detail')
]

删除不需要的成功 View 。

关于python - 用户提交博客文章后重定向到主页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74292984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com