Search code examples
pythondjangolistfunctionreturn

Combined Returns in Python Function Based Views Django


I'm currently building a website with Django and I've gotten to a point where I need to print data on the screen(ListView) and update(UpdateView) data on the same page(template). From what I've found I cant do this easily with the Django generic views so I rewrote my view as a function-based view. This current piece of code updates what I need perfectly with some changes to the HTML.

def DocPostNewView(request, pk):

context = {}

obj = get_object_or_404(DocPost, id=pk)

form = GeeksForm(request.POST or None, instance=obj)

if form.is_valid():
    form.save()
    return HttpResponseRedirect("/" + id)

context["form"] = form

posts = DocPost.objects.all()

return render(request, "my_app/use_template.html", context)

... And this following piece of code lists objects perfectly with some changes to the HTML.

def DocPostNewView(request, pk):

context = {}

obj = get_object_or_404(DocPost, id=pk)

form = GeeksForm(request.POST or None, instance=obj)

if form.is_valid():
    form.save()
    return HttpResponseRedirect("/" + id)

context["form"] = form

posts = DocPost.objects.all()

return render(request, 'my_app/use_template.html', context={'posts': posts})

I just need to combine these and the only real difference is the return command at the bottom of both(the same) functions. HOW CAN I COMBINE THE RETURNS SO I CAN LIST DATA AND UPDATE DATA ON THE SAME PAGE???

Thanks


Solution

  • does this work for you ?

    def DocPostNewView(request, pk=None):
        posts = DocPost.objects.all()
        obj = get_object_or_404(DocPost, id=pk)
        form = GeeksForm(request.POST or None, instance=obj)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/" + id)
        context = {"form":form, "posts":posts}
        return render(request, "my_app/use_template.html", context)
    

    in your templates you could use "posts" to list every post, and your can use "form" to update that specific post,

    the thing is for every update you make you will always be seeing the whole list of posts, if it is that what you want to achieve