我想使用表单创建视图以创建帖子并在同一页面中显示帖子 但是我不知道该怎么办,因为当我添加到view.py表单时,我看不到我的对象,我的意思是“数据库中的帖子”
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from django.http import Http404
from django.shortcuts import render
from django.http import HttpResponse
from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .forms import HomeForm
from .models import simplePost
class IndexView(generic.ListView):
template_name = 'myapp/index.html'
def get_queryset(self):
return simplePost.objects.all()
class ProfileView(CreateView):
template_name = 'myapp/profile.html'
model_name = simplePost
form_class = HomeForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['message'] = simplePost.objects.all() # filter this?
return context
答案 0 :(得分:0)
这是我将如何处理的方法。使用基于类的通用视图消除围绕表单处理(CreateView,UpdateView或FormView)的一些样板代码:https://docs.djangoproject.com/en/2.1/ref/class-based-views/generic-editing/#createview
然后只需将其添加到get_context_data中的上下文变量中,即可获取要显示的所有Post数据。然后,您可以在模板中对其进行迭代,以使用posts上下文变量显示它们。
class ProfileView(CreateView):
template_name = 'myapp/profile.html'
model_name = Profile
form_class = HomeForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['posts'] = simplePost.objects.all() # filter this?
return context
用于显示帖子的模板部分:
{% for post in posts %}
{{ post.body }}
{{ post.author }}
...
{% endfor %}