• Django学习——全局templates引用的问题


    一、问题
    在构建网站的时候我们会用到全局的templates处理错误的网页,此时我们需要对urls进行一个映射,使得在使用的时候避免重复调用。在使用的时候还会产生错误代码:
    第一个是404界面的,第二个是500界面的(Django:2.2.2)

    ?: (urls.E007) The custom handler404 view 'index.views.page_not_found' does not take the correct number of arguments (request, exception).
    ?: (urls.E007) The custom handler500 view 'index.views.page_error' does not take the correct number of arguments (request).

    全局视图


    二、解决
    在一个views中关联html,然后再将views和url建立隐射关系。注意:解决两个问题的关键在于在Django2.2.2下,404的错误不能有参数:exception,但是500的错误必须有exception,如此解决问题。
    1.关联views
    随便选择一个app的views添加如下的代码

    from django.shortcuts import render
    
    # 404
    def page_error(request):
        return render(request, 'error404.html', status=404)
    
    
    # 500
    def page_not_found(request, exception):
        return render(request, 'error404.html', status=500)


    视图:

     

    2.映射

    在项目的url中使用handler404handler500这两个指定的变量来完成数据的映射关系,因为是从index的APP中导入的因此是【from index import views】

    # 设置404、500错误状态码
    from index import views
    
    handler404 = views.page_not_found
    handler500 = views.page_error

     
    视图:


    3.HTML的代码
    其中用{% load staticfiles %}加载全局的资源;用{% static 'imagespk_1.jpg' %}进行资源调用;用href='/music/comment'完成主界面的跳转

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>页面没找到</title>
    {% load staticfiles %}
    </head>
    <body>
    <img src="{% static 'imagespk_1.jpg' %}" width="400" height="400">
    <br>
    <div class="error_main"><a href='/music/comment' class="index">回到首页</a></div>
    </body>
    </html>


    视图:

    4.设置
    最后将setting中的debug改成False就可以观察到结果了。

    三、结果展示

     
    四、总结
    报错信息是由于缺少参数,有时候图片加载有问题,分别刷新一下debug的设置,数据就可以显示出来。
    附上Django的参考文档:
    https://docs.djangoproject.com/en/2.1/ref/settings/#databases

  • 相关阅读:
    Flask路由+视图补充
    Flask登录认证
    Flask
    初识Flask
    redis 注意事项
    Linux安装python和更新pip
    Django 导入配置文件
    redis 5种类型
    redis 支持事务
    数组乱序与数组拆解
  • 原文地址:https://www.cnblogs.com/future-dream/p/11154846.html
Copyright © 2020-2023  润新知