Django2.0:【Django2.0教程】04.使用模版显示内容 视频学习笔记

视频地址:04.使用模版显示内容

查看文章页面:唯一标示id

article/migrations/0001_initial.py的内容如下:

# Generated by Django 2.0.5 on 2018-05-11 06:54

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Article',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=30)),
                ('content', models.TextField()),
            ],
        ),
    ]
title和content是在article/models.py中定义的属性,而此处多了一个id,且为primary key,即主键。那么这个id就为唯一标示。 在article/views.py中写入如下内容:
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def article_detail(request, article_id):
    return HttpResponse("文章id: %s" % article_id)
并在mysite/urls.py中做如下修改:
from django.contrib import admin
from django.urls import path
from . import views
from article.views import article_detail

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),
    path('article/<article_id>', article_detail, name="article_detail"),
]

<article_id>表示变量article_id,变量名需与article_detail()方法中的参数(article_id)名相同。

启动服务器,浏览器中分别打开网址 http://http://127.0.0.1:8000/article/1http://http://127.0.0.1:8000/article/2http://http://127.0.0.1:8000/article/3。article_detail()方法接收到参数article_id并通过HttpResponse返回,显示出来。

objects:获取模型属性

可以通过模型的objects获取或操作模型的对象。修改article/views.py如下:

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

# Create your views here.
def article_detail(request, article_id):
    article = Article.objects.get(id=article_id)
    return HttpResponse("<h2>文章标题: %s</h2><br>文章内容: %s" % (article.title, article.content))

可以打开网页 http://http://127.0.0.1:8000/article/1 查看效果。

如果访问的文章不存在,则可以显示404页面。修改article/views.py如下:

from django.shortcuts import render
from django.http import HttpResponse, Http404
from .models import Article

# Create your views here.
def article_detail(request, article_id):
    try:
        article = Article.objects.get(id=article_id)
    except Article.DoesNotExist:
        raise Http404("不存在")
    return HttpResponse("<h2>文章标题: %s</h2><br>文章内容: %s" % (article.title, article.content))
显示页面如下:

可以按照提示,把mysite.settings.py中的DEBUG设为False,以不打印出错误信息,显示常见的404页面。

使用模板:前后端分离

在article/下新建目录templates,这个目录是Django在mysite/settings.py中规定好的。也就是这块代码:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

BACKEND指定模板系统;DIRS可以自己指定目录;APP_DIRS为True表明APP中的templates目录是有效的。

修改article/views.py:

from django.shortcuts import render
from django.http import HttpResponse, Http404
from .models import Article

# Create your views here.
def article_detail(request, article_id):
    try:
        article = Article.objects.get(id=article_id)
        context = {}
        context['article_obj'] = article
        return render(request, "article_detail.html", context)
    except Article.DoesNotExist:
        raise Http404("不存在")
render()方法需要三个参数,第一个为request,第二个为模板页面,第三个为一个字典。 在article/templates下新建html文件:
<html>
    <head>
    </head>
    <body>
        <h2>{{ article_obj.title }}</h2>
        <hr>
        <p>{{ article_obj.content }}</p>
    </body>
</html>
“{{”和“}}”中使用字典context传入的对象。打开页面 http://http://127.0.0.1:8000/article/1。

可以在articl.views.py中使用render_to_response()方法,该方法是render()方法的简化;可以使用get_object_or_404()方法简化代码,第一个参数是模型,第二个参数是条件,可以写主键id=article_id,如果不知道主键的名字,则可以用pk=article_id,pk为primary key的缩写。

from django.shortcuts import render_to_response, get_object_or_404
from .models import Article

# Create your views here.
def article_detail(request, article_id):
    article = get_object_or_404(Article, pk=article_id)
    context = {}
    context['article_obj'] = article
    return render_to_response("article_detail.html", context)

获取文章列表

修改article/views.py内容如下:
from django.shortcuts import render_to_response, get_object_or_404
from .models import Article

# Create your views here.
def article_detail(request, article_id):
    article = get_object_or_404(Article, pk=article_id)
    context = {}
    context['article_obj'] = article
    return render_to_response("article_detail.html", context)

def article_list(request):
    articles = Article.objects.all()
    context = {}
    context['articles'] = articles
    return render_to_response("article_list.html", context)
新建article/templates/article_list.html:
<html>
    <head>
    </head>
    <body>
        {{ articles }}
    </body>
</html>
访问 http://http://127.0.0.1:8000/article/

这不是想要的结果。

要通过循环列表读取。使用模板标签“{%”和“%}”。
修改article/templates/article_list.html:

<html>
    <head>
    </head>
    <body>
        {% for article in articles %}
            <a href="/article/{{ article.pk }}">{{ article.title }}</a>
            <!-- 或者使用
            <a href="{% url 'article_detail' article.pk %}">{{ article.title }}</a>
            article_detail为在mysite/urls.py指定的name
            -->
            <br>
        {% endfor %}
    </body>
</html>

总urls包含app的urls

当项目有多个APP时,把所有url放在一个总得urls.py中显得不合适。可以为每个APP创建urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.article_list, name="article_list"), # localhost:8000/article/
    path('<int:article_id>', views.article_detail, name="article_detail"), # localhost:8000/article/1
]

mysite/urls.py修改为:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),
    path('article/', include('article.urls')),
]

猜你喜欢

转载自blog.csdn.net/zhangk9509/article/details/80283588