如何从View模型中获取(对象发布)响应。我已尝试对下面的代码进行哈希处理,以确保代码能够正常工作并成功。如何获得响应并使所有对象显示在View模型案例中?
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
from django.views.generic import View
from .forms import PostForm
from .models import Post
class PostView(View):
all_objects = Post.objects.all()
post_form = PostForm
template_name = 'myapp/index.html'
def get(self, request):
post_form = self.post_form(None)
return render(request, self.template_name, {'form': post_form})
def post(self, request):
post_form = self.post_form(request.POST)
if post_form.is_valid():
post_form.save()
return redirect('myapp:index')
return render(request, self.template_name, {'form': post_form, 'all_objects': self.all_objects})
'''
def index(request):
all_objects = Post.objects.all()
post_form = PostForm
if request.method == "POST":
post_form = PostForm(request.POST)
if post_form.is_valid():
post_form.save()
return render(request, 'myapp/index.html', {'form': post_form, 'all_objects': all_objects})
return render(request, 'myapp/index.html', {'form': post_form, 'all_objects': all_objects})
'''