简体   繁体   中英

Django { %include% } HTML not rendering correctly

I am new to Django and Python, please forgive me if this is a noobie question. I have an app where I have 3 views:

#views.py

from django.shortcuts import render_to_response
from django.shortcuts import render
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
from acme.acmetest.models import Player
from acme.acmetest.models import PickForm

def playerAdd(request, id=None):
    form = PickForm(request.POST or None,
                       instance=id and Player.objects.get(id=id))

    if request.method == 'POST' and form.is_valid():
        form.save()
        return HttpResponseRedirect('/draft/')

    return render(request, 'makepick.html', {'form':form})

def draftShow(request):
    draft_list = Player.objects.all()
context_instance=RequestContext(request)
    return render_to_response('listpicks.html', {'draft_list' :draft_list})

def draftPage(request):
    return render(request, 'pickpage.html')

The playerAdd and draftShow views render correctly when they are call on their own in a browser (mapped to separate URLs on separate HTML documents). The draftPage view calls an HTML page:

pickpage.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML lang="en">
<head>
    <title>PickPage</title>
</head>
<body>

{% include "makepick.html" %}
{% include "listpicks.html" %}

</body>
</HTML>

When I call this page, I only get part of the other two html pages. I get the button on the form, but not the field in which to enter test and I get the text of the listpicks, but not the list that is pulled from the database. These are just html pages, and as I said earlier they work when I call them on their own.

Thank you for you help.

dp

Your problem is that you're confusing includes with views.

When you use an include all that happens is the html for that template is inserted at that point.

There's no relation to other views that use the template you're including. So you have to specify the context for the included templates in the view you're using.

So in your case, the context from playerAdd and draftShow isn't available, because you haven't added it to the render method in draftPage.

def draftPage(request):
    form = PickForm()
    draft_list = Player.objects.all()
    context = {
        'form':form,
        'draft_list' :draft_list,
    }
    return render(request, 'pickpage.html', context)

Will give you what you're after in your view. Just make sure that the form submits to the playerAdd view to process it correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM