Django show render_to_response in template

邮差的信 提交于 2019-12-22 05:54:40

问题


Hello and thank you in advance.

I know this is total noob question, and I have searched in the various forum and read and re-read the documentation, so please be gentle.

I have a view:

#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))

    # Save new/edited pick
    if request.method == 'POST' and form.is_valid():
        form.save()
        return HttpResponseRedirect('/draft/')

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

def draftShow(request):
    draft_list = ['1', 'hello', 'test', 'foo', 'bar']
    #draft_list = Player.objects.all()
    #return render_to_response('makepick.html', {'draft_list' :draft_list}, context_instance=RequestContext(request))
    return render_to_response('makepick.html', {'draft_list' :draft_list})

I am trying to get it to render to a template .html page:

#makepick.html

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

    <form method="POST" action="">
        {% csrf_token %}
        <table>{{ form }}</table>
        <input type="submit" value="Draft Player" 
    </form><br /><br /> 

Your picks so far:<br />
{% for draft in draft_list %}
    {{ draft.playernumber }}
{% endfor %}

</body>
</HTML>

Where playernumber is field in the model class "Player" in models.py.

#urls.py

from django.conf.urls.defaults import patterns, include, url
from acme.acmetest import views


urlpatterns = patterns('',
    ('^$', 'acme.acmetest.views.playerAdd'),
)

Thank you for your help!

dp


回答1:


Well, it looks like your template is rendering fine. So you'll have to see if draft_list actually contained anything and what playernumber is for each object that was grabbed.

In the root directory of your project, run:

python manage.py shell

Now that you're in the shell, to test whether there are actually any Player objects in your database and see what the playernumber property of each object returns:

from acme.acmetest.models import Player
draft_list = Player.objects.all()
for draft in draft_list:
    print draft.playernumber



回答2:


Make sure that makepick.hmtl is in your apps templates directory, or in your TEMPLATE_DIR.

You can check in your view to verify that Player.objects.all() is actually returning something. Make sure playernumber is an actual property of the Player object.



来源:https://stackoverflow.com/questions/9200880/django-show-render-to-response-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!