【django2.0】04.使用模板显示内容

B站“再敲一行代码”发布的【django2.0教程】的笔记

视频地址:【django2.0】04.使用模板显示内容

如何通过一个处理方法去处理文章–文章唯一标识

一、查看文章页面

创建处理方法:
编辑G:\Webprojects\mysite\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)

编辑G:\Webprojects\mysite\mysite中的url.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/<int:article_id>', article_detail,name="article_detail"),
]

启动服务器(python manage.py runserver),在浏览器输入http://127.0.0.1:8000/article/1
在这里插入图片描述

二、objects

模型的objects是获取或操作模型的对象
Article.objects.get(条件)
Article.objects.all()
Article.objects.filter(条件)

编辑views.py文件:

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)

在这里插入图片描述
因为admin页面只有三条数据,所以输入5时会报错,这里采用异常处理:

from django.shortcuts import render
from django.http import HttpResponse
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:
        return HttpResponse("不存在!") 
    return HttpResponse("<h2>文章标题: %s</h2> </br>文章内容: %s" % (article.title, article.content))

在这里插入图片描述

一般情况下我们不采取这种方式,而是引入Http404

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("no exist") 
    return HttpResponse("<h2>文章标题: %s</h2> </br>文章内容: %s" % (article.title, article.content))

在这里插入图片描述

三、使用模板

前端页面和后端代码分离,降低耦合性

G:\Webprojects\mysite\article页面创建文件夹templates
这个文件夹django已经规定好了,规定在G:\Webprojects\mysite\mysite的settings里,如下:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,  #templates下的模板文件可以读取的到
        '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',
            ],
        },
    },
]

文件夹templates中创建article_detail.html (注意是html文件而不是txt文件)

<html>
<head>
<body>
    <h2>{{article_obj.title}}</h2>
    <p>{{article_obj.content}}</p>
</body>
</head>
</html>

1.编辑views.py文件(使用render方法)

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("no exist") 

页面效果:
在这里插入图片描述
2.另一种方法(使用render_to_response)(两选一即可,效果相同)
编辑views.py文件

from django.shortcuts import render, render_to_response
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)
        return render_to_response("article_detail.html", context)
    except Article.DoesNotExist:
        raise Http404("no exist") 

3.优化代码
get_object_or_404可以在G:\Webprojects\venv\Lib\site-packages\django中的shortcuts.py中查看,具体如下:
(另:如果不是在虚拟环境中安装django,需要在Python安装路径下的\Lib\site-packages\django中的shortcuts.py中查看)

def get_object_or_404(klass, *args, **kwargs):
    """
    Use get() to return an object, or raise a Http404 exception if the object
    does not exist.

    klass may be a Model, Manager, or QuerySet object. All other passed
    arguments and keyword arguments are used in the get() query.

    Like with QuerySet.get(), MultipleObjectsReturned is raised if more than
    one object is found.
    """
    queryset = _get_queryset(klass)
    if not hasattr(queryset, 'get'):
        klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
        raise ValueError(
            "First argument to get_object_or_404() must be a Model, Manager, "
            "or QuerySet, not '%s'." % klass__name
        )
    try:
        return queryset.get(*args, **kwargs)
    except queryset.model.DoesNotExist:
        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)

使用get_object_or_404优化代码后的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)  #pk是主键的缩写
    context = {}
    context['article_obj'] = article
    return render_to_response("article_detail.html", context)

四、文章列表

编辑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)  #pk是主键的缩写
    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)

文件夹templates中创建article_list.html (注意是html文件而不是txt文件)

<html>
<head>
<body>
    {% for article in articles %}
    	<p>{{ article.title }}</p> 
    {% endfor %}
</body>
</head>
</html>

编辑总的urls.py文件

from django.contrib import admin
from django.urls import path
from . import views
from article.views import article_detail, article_list  #加入

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),
    path('article/<int:article_id>', article_detail,name="article_detail"),
    path('article/', article_list,name="article_list"),  #加入
]

页面效果:
在这里插入图片描述
点击one实现页面跳转:
方法1.编辑article_list.html :

{% for article in articles %}
    <a href="/article/{{ article.pk }}">{{ article.title }}</a> 
{% endfor %}

在这里插入图片描述
方法2.编辑article_list.html :
使用了urls文件中的name=“article_detail”

{% for article in articles %}
    <a href="{% url 'article_detail' article.pk %}">{{ article.title }}</a> 
{% endfor %}

五、总urls(路由)包含app的urls

G:\Webprojects\mysite\article中新建urls.py

from django.urls import path
from . import views 

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

删掉对应总的urls.py中的path和from引用,并加入APP中的路由,修改后:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),
    path('article/', include('article.urls')),
]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值