Django視圖和URL配置

  使用Django,你會用不一樣的方法來講明這兩件事 頁面的內容是靠view function(視圖函數) 來產生,URL定義在 URLconf 中。首先,咱們先寫一個Hello World視圖函數。html

  python3.6 + django 2.2.2python

1. 第一份視圖正則表達式

建立views.pydjango

from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello World")
View Code

代碼說明:ide

  • 首先,咱們從 django.http 模塊導入(import) HttpResponse 類。
  • 接下來,咱們定義一個叫作hello 的視圖函數。每一個視圖函數至少要有一個參數,一般被叫做request。 這是一個觸發這個視圖、包含當前Web請求信息的對象,是類django.http.HttpRequest的一個實例。在這個示例中,咱們雖然不用request作任何事情,然而它仍必須是這個視圖的第一個參數。

2. 第一個URLconf函數

   URLconf 就像是 Django 所支撐網站的目錄。 它的本質是 URL 模式以及要爲該 URL 模式調用的視圖函數之間的映射表。 你就是以這種方式告訴 Django,對於這個 URL 調用這段代碼,對於那個 URL 調用那段代碼。 例如,當用戶訪問/foo/時,調用視圖函數foo_view(),這個視圖函數存在於Python模塊文件view.py中。網站

from django.conf.urls.defaults import *
from spider.views import hello
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.hello),
    path('hello/', views.hello),
]
View Code

代碼說明:url

  • 首先,咱們從模塊 (在 Python 的 import 語法中, spider/views.py 轉譯爲 spider.views ) 中引入了 hello視圖。 (這假設spider/views.py在你的Python搜索路徑上。關於搜索路徑的解釋,請參照下文。)spa

  • 接下來,咱們爲urlpatterns加上一行: path(‘hello/’, views.hello), 這行被稱做URLpattern,它是一個Python的元組。元組中第一個元素是模式匹配字符串(正則表達式);第二個元素是那個模式將使用的視圖函數。code

3. 動態內容

  讓Django視圖顯示當前日期和時間。

  spider/views.py的代碼以下:

def current_datetime(request):
    now = datetime.datetime.now()
    return render_to_response('current_datetime.html', {'current_date': now})


def hours_ahead(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    return render_to_response('hours_ahead.html', {'hour_offset': offset, 'next_time': dt})
View Code

  代碼說明:current_datetime 視圖函數顯示當前時間。hours_ahead根據輸入的值計算要顯示的時間,這裏作了容錯處理,若是輸入的非整型則返回一個404給用戶。

  templates/current_datetime.html 的代碼以下:

# base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <h1>My helpful timestamp site</h1>
    {% block content %}{% endblock %}
    {% block footer %}
    <hr>
    <p>Thanks for visiting my site.</p>
    {% endblock %}
</body>
</html>

# current_datetime.html
{% extends "base.html" %}

{% block title %}The current time{% endblock %}

{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}
View Code

  templates/hours_head.html 的代碼以下:

{% extends "base.html" %}

{% block title %}Future time{% endblock %}

{% block content %}
<p>In {{ hour_offset }} hour(s), it will be {{ next_time }}.</p>
{% endblock %}
View Code

   urls.py函數代碼以下:

from django.contrib import admin
from django.urls import path
from spider import views
from books import views as bk
from contact import views as ct

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.hello),
    path('hello/', views.hello),
    path('time/', views.current_datetime),
    path('time/plus/<offset>/', views.hours_ahead),
]
View Code

  代碼說明: 導入視圖views.py對應的視圖函數,定義了兩個url顯示時間和日期並對應匹配到各個視圖函數。

相關文章
相關標籤/搜索