zoukankan      html  css  js  c++  java
  • 编写实际执行的视图

    编写实际执行的视图
    
    polls/views.py
    from django.http import HttpResponse
    
    from .models import Question
    
    
    def index(request):
        latest_question_list = Question.objects.order_by('-pub_date')[:5]
        output = ', '.join([q.question_text for q in latest_question_list])
        return HttpResponse(output)
    	
    
    
    这里有一个问题:页面的设计被硬编码在视图中,如果你想要更改页面的外观,就是编辑这段Python代码。
    
    将以下的代码放入模板文件:
    
    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 %}
    现在让我们更新polls/views.py中的index视图来使用模板:
    
    polls/views.py
    from django.http import HttpResponse
    from django.template import loader
    
    from .models import Question
    
    
    def index(request):
        latest_question_list = Question.objects.order_by('-pub_date')[:5]
        template = loader.get_template('polls/index.html')
        context = {
            'latest_question_list': latest_question_list,
        }
        return HttpResponse(template.render(context, request))
    
    
    
    
  • 相关阅读:
    vuejs 实战 双向数据绑定
    ubuntu16安装cuda,cudnn,gpu版opencv
    ubuntu编译安装nginx并且配置流服务器
    安装使用mongodb
    c++ 编译安装ffmpeg
    apache2 日志文件太大的解决方案
    sql注入
    制作自己的电子词典
    python传递可变参数
    工厂模式
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13348296.html
Copyright © 2011-2022 走看看