django官方文档3.0学习笔记 03

视图的创建

  • Django中,视图表现为一个python函数(polls.py)
  • 根据用户请求的URL来使用那个视图(urls.py)

匹配变量

# urls.py中配置URL
urlpatterns = [
    path('<int:question_id>/', views.detail, name='detail'),
]
# views.py中引用变量
def detail(request, question_id):
   return HttpResponse("You're looking at question %s." % question_id)

模板渲染和数据处理

  • 模版存放目录(polls/templates/)

  • 模版载入配置(传递字典数据context)

    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))
    
  • 快捷函数重写index()视图

    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)
    

抛出错误404

def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, 'polls/detail.html', {'question': question})
  • 快捷函数get_object_or_404( )

    question = get_object_or_404(Question, pk=question_id)
    

模板系统

  • 循环调用: {% for … in … %} {% endfor %}

  • 变量:{{ xxx }}

  • 模板中替换URL

    替换前

    <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    

    替换后

    <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
    
  • URL 名称添加命名空间,视图不唯一,指向具体的应用视图

    无指向

    <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
    

    指向具体命名空间

    <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
    

学习资料连接:django官方文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值