Reputation: 65
I have been researching on how to render a single template using two class based views and I have not found any material addressing the same. For instance the home.html template with a functionality of creating a new post and at the same time listing all the posts in the database. How do I implement such functionality.
class BlogCreateView(CreateView):
model = Post
template_name = 'home.html'
fields = ['title', 'body']
class BlogListView(ListView):
model = Post
template_name = 'home.html'
Upvotes: 2
Views: 576
Reputation: 673
Class-based views are great in theory, but sometimes they just make things overly complicated. You can use this function-base-view which is easy.
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})
Upvotes: 2