美文网首页
django入门教程4 建立视图(View)并设置路由(URLc

django入门教程4 建立视图(View)并设置路由(URLc

作者: BlueJack | 来源:发表于2018-10-25 15:07 被阅读0次

创建模板

首先,在 polls 目录里创建一个 templates 目录。Django 将会在这个目录里查找模板文件。
在 templates 目录里,再创建一个目录 polls,然后在其中新建一个文件 index.html 。换句话说,你的模板文件的路径应该是 polls/templates/polls/index.html 。因为 Django 会寻找到对应的 app_directories ,所以你只需要使用 polls/index.html 就可以引用到这一模板了。
将下面的代码输入到刚刚创建的模板文件中:

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

这是 Question 列表页面的模板。同样,再创建详情(Detail)页面模板 polls/templates/polls/detail.html:

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

创建视图(View)

打开 polls/views.py 文件编辑:

from django.views import generic
from .models import Question


class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'question_list'

    def get_queryset(self):
        return Question.objects.order_by('-pub_date')


class DetailView(generic.DetailView):
    template_name = 'polls/detail.html'
    model = Question

设置路由(URLconf)

在 polls 目录新建 urls.py 文件,你的应用目录现在看起来应该是这样:

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    urls.py
    views.py

在 polls/urls.py 中,输入如下代码:

from django.urls import path
from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
]

注:其中的 pk 即主键(Primary Key)。通过主键查找是最常见的情况,因此Django提供了一个主键精确查找的快捷方式:pk

下一步是要在根 URLconf 文件中引入我们创建的 polls.urls 模块。在 jsite/urls.py 文件的 urlpatterns 列表里插入一个 include(), 如下:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

运行服务器:

python manage.py runserver

用你的浏览器访问 http://localhost:8000/polls/,应该能够看见展示 Question 列表的页面了,点击其中的列表项,就会进入详情页面。

相关文章

网友评论

      本文标题:django入门教程4 建立视图(View)并设置路由(URLc

      本文链接:https://www.haomeiwen.com/subject/wonqtqtx.html