python web开发——Django模板

Django 模型API

可以通过命令的方式访问Django模型,也就是数据库。

python manage.py shell
>>> import django
>>> django.setup()

查询

from polls.models import Question,Choice
Question.objects.all()

修改视图输出所有问题

from django.shortcuts import render
from .models import Question
def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list':latest_question_list }
    return render(request,'polls/index.html',context)

创建模板文件

在polls/templates目录下面创建一个polls文件夹,在其中创建一个index.html文件,内容如下:

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href = "/polls/{{ question_id}}/">{{ question.question_text}}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

修改视图文件

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = RequestContext(request,{'latest_question_list':latest_question_list,})
    return HttpResponse(template.render(context))

detail

创建一个detail.html文件。

<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
<% endfor %>
</ul>

修改视图文件

def detail(request,question_id):
    question = get_object_or_404(Question,pk = question_id)
    return render(request,'polls/detail.html',{'question':question})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值