I'm very new to using Django and coding in general. So I have figured out how to make the form submit to my database but now when it submits, it just brings you to the blank blog_post view and I'm not understanding how to redirect correctly.
here is the 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")
urls.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'),
]
I have tried a few variations of httpresponseredirect and redirect but i just cant wrap my head around it, nor can i find it online. Any help is greatly appreciated.
CodePudding user response:
You can redirect to the home in success
with:
from django.utils import redirect
def success(request):
return redirect('blog:home')
You should however only redirect in case the form was successful, so:
def blog_post(request):
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('blog:home') #