0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly I knew I was close but thanks for teaching me how to finish it. I haven't been getting a lot of constructive answers lately, it's people like you keeping these forums going.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.