Django part3

视图(views)

视图是Django应用程序中的一种“类型”网页,通常用于特定功能并具有特定模板。
在我们的投票应用程序(polls)中,我们将有以下四个视图:

Question “index” page – 显示最近几个问题。
Question “detail” page – 显示问题文本,没有结果,但有一个要投票的表单。
Question “results” page – 显示特定问题的结果。
Vote action – 处理对特定问题中特定选择的投票。

文件结构

在这里插入图片描述

polls/views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.http import Http404
from .models import Question
from django.template import loader
# Create your views here.
# Django模板使用  https://docs.djangoproject.com/en/2.2/topics/templates/


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


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


def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)


def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

polls.urls

from django.urls import path

from . import views

app_name = 'polls'
# 增加命名空间,区分url
urlpatterns = [
    path('', views.index, name='index'),
    # 获取最新的问题,默认作为初始页
    path('<int:question_id>/', views.detail, name='detail'),
    # 获取某个问题的详情页
    path('<int:question_id>/results/', views.results, name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

polls/templates/polls/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>polls</title>
</head>
<body>
{% 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 %}
</body>
</html>

polls/templates/polls/detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>polls 详情页</title>
</head>
<body>
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
</body>
</html>

运行项目

py manage.py runserver

运行截图

在这里插入图片描述
点击后
在这里插入图片描述

参考博客

Django表单
Django传值
用python专业版创建Django项目
Django创建一个应用项目
Django app2

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值