Django - 创建一个Web投票应用 - 视图和模板

编写视图

from django.shortcuts import render
from django.http import HttpResponse


def index(request):
    return HttpResponse("这里是投票站点")


# 问卷的详细文本内容
def detail(request, question_id):
    return HttpResponse("你看到的问题是: %s." % question_id)


# 显示某个问卷的投票结果
def results(request, question_id):
    response = "你看到的是%s问题的投票结果"
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("你在对%s问题进行投票" % question_id)

配置路由

from django.urls import path
from . import views

urlpatterns = [
    # 例如 /polls/
    path('', views.index, name='index'),
    # 例如 /polls/6
    path('<int:question_id>', views.detail, name='detail'),
    # 例如 /polls/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # 例如:
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

访问 localhost:8000/polls/34/ 将调用detail函数
当有人访问/poll/34/地址时, Django将首先加载mysite.urls模块. 在该文件中, Django发现了urlpatterns变量, 于是在其内按顺序进行匹配, 匹配到了polls/, 就裁去url中匹配的文本polls/, 将剩下的文本 34/ 传递给polls.urls进行下一步处理, 在polls.urls中, 匹配到了<int:question_id>/, 然后调用对应的detail视图.
<int:question_id>/, 使用尖括号 捕获 这部分URL, 且以关键字参数的形式发送给视图函数.

修改index视图, 根据发布日期显示最近的5个投票问卷

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)

创建模板系统

在polls目录下创建一个新的templates目录,Django会在它里面查找模板文件。再创建一个新的子目录名叫polls.
index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</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>没有投票</p>
    {% endif %}
</body>
</html>

现在index视图没有传数据到前端 , 修改index视图, 让index.html文件生效

views.py

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

render()函数的第一个位置参数是请求对象, 第二个位置参数是模板文件, 第三个可选参数是一个字典, 包含需要传递给模板的数据.

返回404错误

# 问卷的详细文本内容
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

get_object_or_404() 方法将一个Django模型作为第一个位置参数, 后面可以跟上任意数量的关键字参数.

修改detail模板

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

删除模板中硬编码的URLS

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    {% if latest_question_list %}
        <ul>
        {% for question in latest_question_list %}
            <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>没有投票</p>
    {% endif %}
</body>
</html>

URL names的命名空间

可以在urls.py文件的开头部分, 添加一个app_name的变量来指定该应用的命名空间

from django.urls import path
from . import views


# 指定app名称
app_name = 'polls'


urlpatterns = [
    # 例如 /polls/
    path('', views.index, name='index'),
    # 例如 /polls/6
    path('<int:question_id>', views.detail, name='detail'),
    # 例如 /polls/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # 例如:
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

然后把代码修改的严谨一些

polls/templates/polls/index.html 中的

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

修改为

<li>
	<a href="{% url 'poll:detail' question.id %}">
		{{ question.question_text }}
	</a>
</li>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值