两个基于 django 通用 Class 的视图到同一个模板中
Two django generic Class Based Views into the same template
我一直在研究如何使用两个基于 class 的视图来呈现单个模板,但我没有找到任何 material 解决相同问题的方法。例如,home.html 模板具有创建新 post 并同时列出数据库中所有 post 的功能。我如何实现这样的功能。
class BlogCreateView(CreateView):
model = Post
template_name = 'home.html'
fields = ['title', 'body']
class BlogListView(ListView):
model = Post
template_name = 'home.html'
基于 Class 的视图在理论上很棒,但有时它们只会让事情变得过于复杂。你可以使用这个function-base-view,很简单
def list_and_create(request):
if request.method == 'POST':
form = FormNameYouCreated(request.POST or None)
if form.is_valid():
form.save()
# notice this comes after saving the form to pick up new objects
post = Post.objects.all()
return render(request, 'home.html', {'post': post, 'form': form})
我一直在研究如何使用两个基于 class 的视图来呈现单个模板,但我没有找到任何 material 解决相同问题的方法。例如,home.html 模板具有创建新 post 并同时列出数据库中所有 post 的功能。我如何实现这样的功能。
class BlogCreateView(CreateView):
model = Post
template_name = 'home.html'
fields = ['title', 'body']
class BlogListView(ListView):
model = Post
template_name = 'home.html'
Class 的视图在理论上很棒,但有时它们只会让事情变得过于复杂。你可以使用这个function-base-view,很简单
def list_and_create(request):
if request.method == 'POST':
form = FormNameYouCreated(request.POST or None)
if form.is_valid():
form.save()
# notice this comes after saving the form to pick up new objects
post = Post.objects.all()
return render(request, 'home.html', {'post': post, 'form': form})