Hướng dẫn how do i return an html file in django? - làm cách nào để trả lại tệp html trong django?

Đầu tiên, bạn cần thực hiện một số cài đặt để tạo khuôn mẫu:

Tạo thư mục "Mẫu" trong rootDirectory, trong đó Manage.py được đặt sau khi bạn tạo dự án của mình. Sau đó chuyển đến Cài đặt.py, trong phần Mẫu Nhập thư mục của thư mục Mẫu. Mã hóa cứng không được khuyến nghị vì nếu bạn gửi dự án cho bạn của bạn, bạn của bạn sẽ không thể chạy nó. Nên như thế này:root directory, where manage.py is located after you created your project. Then go to settings.py , in the TEMPLATES section enter the directory of templates folder. Hard coding is not recommended because if you send your project to your friend, your friend won't be able to run it. Should be like this:

TEMPLATES = [
 {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,"templates")],
        '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',
            ],
        },
    },
]

Giả sử rằng bạn có nhà.html và about.html có trong thư mục mẫu:home.html and about.html have in templates folder:

urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('about/',views.aboutview),
    path('',views.homeview),
]

views.py

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

def aboutview(request):
  return render(request,"home.html")
def homeview(request):
  return render(request,"about.html")

Ứng dụng web Morden đều được thiết kế với mẫu MVC (mô hình, chế độ xem, bộ điều khiển). Nhưng trong Django, tên mẫu là MTV (mô hình, mẫu, chức năng xem). Vì vậy, trong Django, HTML mẫu là chế độ xem và chức năng xem đóng vai trò của bộ điều khiển. Bài viết này sẽ cho bạn biết cách tạo chức năng mẫu và xem chức năng trong ứng dụng Django với ví dụ và cách trả về tệp HTML mẫu dưới dạng phản hồi trong chức năng xem Django. Nếu bạn muốn tìm hiểu quá trình hoàn chỉnh về cách tạo một trang web với Django, bạn có thể đọc cách tạo một trang web với Python và Django.

Chức năng Django View được xác định trong tệp Django APP Views.py. Hàm này sẽ chấp nhận đối tượng

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

def aboutview(request):
  return render(request,"home.html")
def homeview(request):
  return render(request,"about.html")
1 là tham số đầu tiên, nó cũng có thể chấp nhận các tham số khác được truyền từ URL yêu cầu (bạn có thể đọc bài viết cách truyền nhiều tham số qua URL trong Django). Ở cuối hàm Chế độ xem, nó sẽ trả về một đối tượng
from django.http import HttpResponse
from django.shortcuts import render

def aboutview(request):
  return render(request,"home.html")
def homeview(request):
  return render(request,"about.html")
2 được tạo bởi lớp httpresponse hoặc shortcut render () với tệp mẫu HTML như bên dưới.views.py file. This function will accept a
from django.http import HttpResponse
from django.shortcuts import render

def aboutview(request):
  return render(request,"home.html")
def homeview(request):
  return render(request,"about.html")
1
object as the first parameter, it can also accept other parameters which are passed from the request url ( you can read article How To Pass Multiple Parameters Via Url In Django ). At the end of the view function, it will return a
from django.http import HttpResponse
from django.shortcuts import render

def aboutview(request):
  return render(request,"home.html")
def homeview(request):
  return render(request,"about.html")
2
object either created by HttpResponse class or render() shortcut with a html template file like below.

1. Trả về đối tượng httpresponse được tạo bởi lớp django.http.httpresponse.

from django.http import HttpResponse

def index_page(request):
    # create a HttpResponse object and return it.
    response = HttpResponse('Hello World', content_type="text/plain")
    return response

2. Trả về đối tượng httpresponse được tạo bởi lối tắt kết xuất.

Xin lưu ý tệp mẫu home_page.html phải được lưu trong Django_project_name (Djangohelloworld) / Mẫu / Django_app_name (DEPT_EMP).home_page.html template file should be saved in django_project_name(DjangoHelloWorld) / templates / django_app_name(dept_emp) folder.

Hướng dẫn how do i return an html file in django? - làm cách nào để trả lại tệp html trong django?

def home_page(request):
    # invoke render shortcut to create HttpResponse object with template html file.
    resp = render(request, 'dept_emp/home_page.html')

    # set reponse headers and values.
    resp['Cache-Control'] = 'public,max-age=100000'
    resp['Vary'] = 'Accept-Encoding'
    return resp

def dept_list(request):
    ......
    # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
    return render(request, 'dept_emp/dept_list.html',
                  {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})

3. Trả về đối tượng httpresponse được tạo bởi django.http.httpresponseredirect.

def login_account(request):
    
    # the HttpResponseRedirect class return a HttpResponse object also, and the response is a redirect response which will change the web browser url.
    response = HttpResponseRedirect('/user/login_success/')
    
    # set cookie to transfer user name to login success page.
    response.set_cookie('user_name', user_name, 3600)
    
    return response

  • Trước
  • Tổng quan: Django
  • Tiếp theo

Bây giờ chúng tôi đã sẵn sàng để thêm mã hiển thị trang hoàn chỉnh đầu tiên của chúng tôi - một trang chủ cho trang web locall Library. Trang chủ sẽ hiển thị số lượng hồ sơ chúng tôi có cho từng loại mô hình và cung cấp các liên kết điều hướng thanh bên đến các trang khác của chúng tôi. Trên đường đi, chúng tôi sẽ có được kinh nghiệm thực tế khi viết các bản đồ và chế độ xem URL cơ bản, nhận hồ sơ từ cơ sở dữ liệu và sử dụng các mẫu.

Prerequisites:Đọc phần giới thiệu Django. Hoàn thành các chủ đề hướng dẫn trước đây (bao gồm Django Hướng dẫn Phần 4: Trang web quản trị Django).
Objective:Tìm hiểu để tạo các bản đồ và chế độ xem URL đơn giản (trong đó không có dữ liệu nào được mã hóa trong URL), lấy dữ liệu từ các mô hình và tạo các mẫu.

Tổng quan

Sau khi chúng tôi xác định các mô hình của mình và tạo một số hồ sơ thư viện ban đầu để làm việc, đã đến lúc viết mã trình bày thông tin đó cho người dùng. Điều đầu tiên chúng tôi cần làm là xác định thông tin nào chúng tôi muốn hiển thị trong các trang của mình và xác định các URL để sử dụng để trả về các tài nguyên đó. Sau đó, chúng tôi sẽ tạo một bản đồ URL, chế độ xem và mẫu URL để hiển thị các trang.

Sơ đồ sau đây mô tả luồng dữ liệu chính và các thành phần cần thiết khi xử lý các yêu cầu và phản hồi HTTP. Như chúng tôi đã triển khai mô hình, các thành phần chính chúng tôi sẽ tạo là:

  • Người lập bản đồ URL để chuyển tiếp các URL được hỗ trợ (và bất kỳ thông tin nào được mã hóa trong URL) đến các chức năng xem thích hợp.
  • Xem các chức năng để lấy dữ liệu được yêu cầu từ các mô hình, tạo các trang HTML hiển thị dữ liệu và trả lại các trang cho người dùng để xem trong trình duyệt.
  • Các mẫu để sử dụng khi hiển thị dữ liệu trong các chế độ xem.

Hướng dẫn how do i return an html file in django? - làm cách nào để trả lại tệp html trong django?

Như bạn sẽ thấy trong phần tiếp theo, chúng tôi có 5 trang để hiển thị, đây là quá nhiều thông tin để ghi lại trong một bài viết. Do đó, bài viết này sẽ tập trung vào cách thực hiện trang chủ và chúng tôi sẽ trình bày các trang khác trong một bài viết tiếp theo. Điều này sẽ cung cấp cho bạn một sự hiểu biết từ đầu đến cuối tốt về cách những người lập bản đồ, quan điểm và mô hình URL hoạt động trong thực tế.

Xác định URL tài nguyên

Vì phiên bản này của Locall Library về cơ bản chỉ đọc cho người dùng cuối, chúng tôi chỉ cần cung cấp một trang đích cho trang web (một trang chủ) và các trang hiển thị danh sách và xem chi tiết cho sách và tác giả.

Các URL mà chúng ta sẽ cần cho các trang của chúng ta là:

  • from django.http import HttpResponse
    from django.shortcuts import render
    
    def aboutview(request):
      return render(request,"home.html")
    def homeview(request):
      return render(request,"about.html")
    
    3 - Trang Home (Index).
  • from django.http import HttpResponse
    from django.shortcuts import render
    
    def aboutview(request):
      return render(request,"home.html")
    def homeview(request):
      return render(request,"about.html")
    
    4 - Danh sách tất cả các cuốn sách.
  • from django.http import HttpResponse
    from django.shortcuts import render
    
    def aboutview(request):
      return render(request,"home.html")
    def homeview(request):
      return render(request,"about.html")
    
    5 - Danh sách tất cả các tác giả.
  • from django.http import HttpResponse
    from django.shortcuts import render
    
    def aboutview(request):
      return render(request,"home.html")
    def homeview(request):
      return render(request,"about.html")
    
    6 - Chế độ xem chi tiết cho một cuốn sách cụ thể, với khóa chính trường là
    from django.http import HttpResponse
    from django.shortcuts import render
    
    def aboutview(request):
      return render(request,"home.html")
    def homeview(request):
      return render(request,"about.html")
    
    7 (mặc định). Ví dụ: URL cho cuốn sách thứ ba được thêm vào danh sách sẽ là
    from django.http import HttpResponse
    from django.shortcuts import render
    
    def aboutview(request):
      return render(request,"home.html")
    def homeview(request):
      return render(request,"about.html")
    
    8.
  • from django.http import HttpResponse
    from django.shortcuts import render
    
    def aboutview(request):
      return render(request,"home.html")
    def homeview(request):
      return render(request,"about.html")
    
    9 - Chế độ xem chi tiết cho tác giả cụ thể với trường chính là
    from django.http import HttpResponse
    from django.shortcuts import render
    
    def aboutview(request):
      return render(request,"home.html")
    def homeview(request):
      return render(request,"about.html")
    
    7. Ví dụ: URL cho tác giả thứ 11 được thêm vào danh sách sẽ là
    from django.http import HttpResponse
    
    def index_page(request):
        # create a HttpResponse object and return it.
        response = HttpResponse('Hello World', content_type="text/plain")
        return response
    1.

Ba URL đầu tiên sẽ trả về trang chỉ mục, danh sách sách và danh sách tác giả. Các URL này không mã hóa bất kỳ thông tin bổ sung nào và các truy vấn tìm nạp dữ liệu từ cơ sở dữ liệu sẽ luôn giống nhau. Tuy nhiên, kết quả mà các truy vấn trả về sẽ phụ thuộc vào nội dung của cơ sở dữ liệu.

Ngược lại, hai URL cuối cùng sẽ hiển thị thông tin chi tiết về một cuốn sách hoặc tác giả cụ thể. Các URL này mã hóa danh tính của mục để hiển thị (được biểu thị bằng

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

def aboutview(request):
  return render(request,"home.html")
def homeview(request):
  return render(request,"about.html")
7 ở trên). Bản đồ URL sẽ trích xuất thông tin được mã hóa và chuyển nó đến chế độ xem và chế độ xem sẽ xác định linh hoạt những thông tin nào sẽ nhận được từ cơ sở dữ liệu. Bằng cách mã hóa thông tin trong URL, chúng tôi sẽ sử dụng một bộ ánh xạ URL, chế độ xem và một mẫu để xử lý tất cả các cuốn sách (hoặc tác giả).

Lưu ý: Với Django, bạn có thể xây dựng URL của mình tuy nhiên bạn yêu cầu - bạn có thể mã hóa thông tin trong phần thân của URL như được hiển thị ở trên hoặc bao gồm các tham số

from django.http import HttpResponse

def index_page(request):
    # create a HttpResponse object and return it.
    response = HttpResponse('Hello World', content_type="text/plain")
    return response
3 trong URL, ví dụ
from django.http import HttpResponse

def index_page(request):
    # create a HttpResponse object and return it.
    response = HttpResponse('Hello World', content_type="text/plain")
    return response
4. Bất cứ cách tiếp cận nào bạn sử dụng, các URL nên được giữ sạch sẽ, hợp lý và có thể đọc được, theo khuyến nghị của W3C. Tài liệu Django khuyến nghị mã hóa thông tin trong phần thân của URL để đạt được thiết kế URL tốt hơn.
With Django, you can construct your URLs however you require — you can encode information in the body of the URL as shown above, or include
from django.http import HttpResponse

def index_page(request):
    # create a HttpResponse object and return it.
    response = HttpResponse('Hello World', content_type="text/plain")
    return response
3 parameters in the URL, for example
from django.http import HttpResponse

def index_page(request):
    # create a HttpResponse object and return it.
    response = HttpResponse('Hello World', content_type="text/plain")
    return response
4. Whichever approach you use, the URLs should be kept clean, logical, and readable, as recommended by the W3C. The Django documentation recommends encoding information in the body of the URL to achieve better URL design.

Như đã đề cập trong tổng quan, phần còn lại của bài viết này mô tả cách xây dựng trang chỉ mục.

Tạo trang chỉ mục

Trang đầu tiên chúng tôi sẽ tạo là trang Index (

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

def aboutview(request):
  return render(request,"home.html")
def homeview(request):
  return render(request,"about.html")
3). Trang chỉ mục sẽ bao gồm một số HTML tĩnh, cùng với "đếm" của các bản ghi khác nhau trong cơ sở dữ liệu. Để thực hiện công việc này, chúng tôi sẽ tạo một ánh xạ URL, chế độ xem và một mẫu.

Lưu ý: Điều đáng để chú ý thêm một chút trong phần này. Hầu hết các thông tin cũng áp dụng cho các trang khác chúng tôi sẽ tạo. It's worth paying a little extra attention in this section. Most of the information also applies to the other pages we'll create.

Ánh xạ URL

Khi chúng tôi tạo trang web Skeleton, chúng tôi đã cập nhật tệp locall Library/urls.py để đảm bảo rằng bất cứ khi nào URL bắt đầu với

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

def aboutview(request):
  return render(request,"home.html")
def homeview(request):
  return render(request,"about.html")
3 được nhận, mô -đun URLConf
from django.http import HttpResponse

def index_page(request):
    # create a HttpResponse object and return it.
    response = HttpResponse('Hello World', content_type="text/plain")
    return response
7 sẽ xử lý chuỗi con còn lại.locallibrary/urls.py file to ensure that whenever a URL that starts with
from django.http import HttpResponse
from django.shortcuts import render

def aboutview(request):
  return render(request,"home.html")
def homeview(request):
  return render(request,"about.html")
3 is received, the URLConf module
from django.http import HttpResponse

def index_page(request):
    # create a HttpResponse object and return it.
    response = HttpResponse('Hello World', content_type="text/plain")
    return response
7 will process the remaining substring.

Đoạn mã sau từ locall Library/urls.py bao gồm mô -đun

from django.http import HttpResponse

def index_page(request):
    # create a HttpResponse object and return it.
    response = HttpResponse('Hello World', content_type="text/plain")
    return response
7:locallibrary/urls.py includes the
from django.http import HttpResponse

def index_page(request):
    # create a HttpResponse object and return it.
    response = HttpResponse('Hello World', content_type="text/plain")
    return response
7 module:

urlpatterns += [
    path('catalog/', include('catalog.urls')),
]

Lưu ý: Bất cứ khi nào Django gặp chức năng nhập

from django.http import HttpResponse

def index_page(request):
    # create a HttpResponse object and return it.
    response = HttpResponse('Hello World', content_type="text/plain")
    return response
9, nó sẽ phân tách chuỗi URL ở ký tự kết thúc được chỉ định và gửi chuỗi con còn lại đến mô -đun URLConf đi kèm để xử lý thêm. Whenever Django encounters the import function
from django.http import HttpResponse

def index_page(request):
    # create a HttpResponse object and return it.
    response = HttpResponse('Hello World', content_type="text/plain")
    return response
9, it splits the URL string at the designated end character and sends the remaining substring to the included URLconf module for further processing.

Chúng tôi cũng đã tạo một tệp trình giữ chỗ cho mô -đun URLConf, có tên là /catalog/urls.py. Thêm các dòng sau vào tệp đó:/catalog/urls.py. Add the following lines to that file:

urlpatterns = [
    path('', views.index, name='index'),
]

Hàm

def home_page(request):
    # invoke render shortcut to create HttpResponse object with template html file.
    resp = render(request, 'dept_emp/home_page.html')

    # set reponse headers and values.
    resp['Cache-Control'] = 'public,max-age=100000'
    resp['Vary'] = 'Accept-Encoding'
    return resp

def dept_list(request):
    ......
    # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
    return render(request, 'dept_emp/dept_list.html',
                  {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
0 xác định như sau:

  • Một mẫu URL, là một chuỗi trống:
    def home_page(request):
        # invoke render shortcut to create HttpResponse object with template html file.
        resp = render(request, 'dept_emp/home_page.html')
    
        # set reponse headers and values.
        resp['Cache-Control'] = 'public,max-age=100000'
        resp['Vary'] = 'Accept-Encoding'
        return resp
    
    def dept_list(request):
        ......
        # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
        return render(request, 'dept_emp/dept_list.html',
                      {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
    
    1. Chúng tôi sẽ thảo luận chi tiết về các mẫu URL khi làm việc trên các quan điểm khác.
  • Hàm xem sẽ được gọi nếu mẫu URL được phát hiện:
    def home_page(request):
        # invoke render shortcut to create HttpResponse object with template html file.
        resp = render(request, 'dept_emp/home_page.html')
    
        # set reponse headers and values.
        resp['Cache-Control'] = 'public,max-age=100000'
        resp['Vary'] = 'Accept-Encoding'
        return resp
    
    def dept_list(request):
        ......
        # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
        return render(request, 'dept_emp/dept_list.html',
                      {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
    
    2, là hàm có tên
    def home_page(request):
        # invoke render shortcut to create HttpResponse object with template html file.
        resp = render(request, 'dept_emp/home_page.html')
    
        # set reponse headers and values.
        resp['Cache-Control'] = 'public,max-age=100000'
        resp['Vary'] = 'Accept-Encoding'
        return resp
    
    def dept_list(request):
        ......
        # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
        return render(request, 'dept_emp/dept_list.html',
                      {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
    
    3 trong tệp Views.py.views.py file.

Hàm

def home_page(request):
    # invoke render shortcut to create HttpResponse object with template html file.
    resp = render(request, 'dept_emp/home_page.html')

    # set reponse headers and values.
    resp['Cache-Control'] = 'public,max-age=100000'
    resp['Vary'] = 'Accept-Encoding'
    return resp

def dept_list(request):
    ......
    # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
    return render(request, 'dept_emp/dept_list.html',
                  {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
0 cũng chỉ định tham số
def home_page(request):
    # invoke render shortcut to create HttpResponse object with template html file.
    resp = render(request, 'dept_emp/home_page.html')

    # set reponse headers and values.
    resp['Cache-Control'] = 'public,max-age=100000'
    resp['Vary'] = 'Accept-Encoding'
    return resp

def dept_list(request):
    ......
    # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
    return render(request, 'dept_emp/dept_list.html',
                  {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
5, đây là một định danh duy nhất cho ánh xạ URL cụ thể này. Bạn có thể sử dụng tên để "đảo ngược" bản đồ, tức là để tạo một URL chỉ vào tài nguyên mà bản đồ được thiết kế để xử lý. Ví dụ: chúng tôi có thể sử dụng tham số tên để liên kết đến trang chủ của chúng tôi từ bất kỳ trang nào khác bằng cách thêm liên kết sau trong một mẫu:

<a href="{% url 'index' %}">Homea>.

Lưu ý: Chúng tôi có thể mã cứng liên kết như trong

def home_page(request):
    # invoke render shortcut to create HttpResponse object with template html file.
    resp = render(request, 'dept_emp/home_page.html')

    # set reponse headers and values.
    resp['Cache-Control'] = 'public,max-age=100000'
    resp['Vary'] = 'Accept-Encoding'
    return resp

def dept_list(request):
    ......
    # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
    return render(request, 'dept_emp/dept_list.html',
                  {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
6), nhưng nếu chúng tôi thay đổi mẫu cho trang chủ của chúng tôi, ví dụ, thành
def home_page(request):
    # invoke render shortcut to create HttpResponse object with template html file.
    resp = render(request, 'dept_emp/home_page.html')

    # set reponse headers and values.
    resp['Cache-Control'] = 'public,max-age=100000'
    resp['Vary'] = 'Accept-Encoding'
    return resp

def dept_list(request):
    ......
    # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
    return render(request, 'dept_emp/dept_list.html',
                  {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
7), các mẫu sẽ không còn liên kết chính xác. Sử dụng ánh xạ URL đảo ngược là mạnh mẽ hơn.
We can hard code the link as in
def home_page(request):
    # invoke render shortcut to create HttpResponse object with template html file.
    resp = render(request, 'dept_emp/home_page.html')

    # set reponse headers and values.
    resp['Cache-Control'] = 'public,max-age=100000'
    resp['Vary'] = 'Accept-Encoding'
    return resp

def dept_list(request):
    ......
    # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
    return render(request, 'dept_emp/dept_list.html',
                  {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
6), but if we change the pattern for our home page, for example, to
def home_page(request):
    # invoke render shortcut to create HttpResponse object with template html file.
    resp = render(request, 'dept_emp/home_page.html')

    # set reponse headers and values.
    resp['Cache-Control'] = 'public,max-age=100000'
    resp['Vary'] = 'Accept-Encoding'
    return resp

def dept_list(request):
    ......
    # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
    return render(request, 'dept_emp/dept_list.html',
                  {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
7) the templates will no longer link correctly. Using a reversed URL mapping is more robust.

Xem (dựa trên chức năng)

Chế độ xem là một hàm xử lý yêu cầu HTTP, lấy dữ liệu cần thiết từ cơ sở dữ liệu, hiển thị dữ liệu trong trang HTML bằng mẫu HTML và sau đó trả về HTML được tạo trong phản hồi HTTP để hiển thị trang cho người dùng. Chế độ xem chỉ mục theo mô hình này - nó tìm hiểu thông tin về số lượng

def home_page(request):
    # invoke render shortcut to create HttpResponse object with template html file.
    resp = render(request, 'dept_emp/home_page.html')

    # set reponse headers and values.
    resp['Cache-Control'] = 'public,max-age=100000'
    resp['Vary'] = 'Accept-Encoding'
    return resp

def dept_list(request):
    ......
    # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
    return render(request, 'dept_emp/dept_list.html',
                  {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
8,
def home_page(request):
    # invoke render shortcut to create HttpResponse object with template html file.
    resp = render(request, 'dept_emp/home_page.html')

    # set reponse headers and values.
    resp['Cache-Control'] = 'public,max-age=100000'
    resp['Vary'] = 'Accept-Encoding'
    return resp

def dept_list(request):
    ......
    # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
    return render(request, 'dept_emp/dept_list.html',
                  {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
9, có sẵn
def home_page(request):
    # invoke render shortcut to create HttpResponse object with template html file.
    resp = render(request, 'dept_emp/home_page.html')

    # set reponse headers and values.
    resp['Cache-Control'] = 'public,max-age=100000'
    resp['Vary'] = 'Accept-Encoding'
    return resp

def dept_list(request):
    ......
    # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
    return render(request, 'dept_emp/dept_list.html',
                  {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
9 và
def login_account(request):
    
    # the HttpResponseRedirect class return a HttpResponse object also, and the response is a redirect response which will change the web browser url.
    response = HttpResponseRedirect('/user/login_success/')
    
    # set cookie to transfer user name to login success page.
    response.set_cookie('user_name', user_name, 3600)
    
    return response
1 mà chúng tôi có trong cơ sở dữ liệu và chuyển thông tin đó đến một mẫu để hiển thị.

Mở Catalog/ViewS.Py và lưu ý rằng tệp đã nhập hàm tắt Render () để tạo tệp HTML bằng cách sử dụng mẫu và dữ liệu:catalog/views.py and note that the file already imports the render() shortcut function to generate an HTML file using a template and data:

from django.shortcuts import render

# Create your views here.

Dán các dòng sau ở dưới cùng của tệp:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('about/',views.aboutview),
    path('',views.homeview),
]
0

Dòng đầu tiên nhập các lớp mô hình mà chúng tôi sẽ sử dụng để truy cập dữ liệu trong tất cả các quan điểm của chúng tôi.

Phần đầu tiên của hàm xem có được số lượng bản ghi bằng thuộc tính

def login_account(request):
    
    # the HttpResponseRedirect class return a HttpResponse object also, and the response is a redirect response which will change the web browser url.
    response = HttpResponseRedirect('/user/login_success/')
    
    # set cookie to transfer user name to login success page.
    response.set_cookie('user_name', user_name, 3600)
    
    return response
2 trên các lớp mô hình. Nó cũng có một danh sách các đối tượng
def home_page(request):
    # invoke render shortcut to create HttpResponse object with template html file.
    resp = render(request, 'dept_emp/home_page.html')

    # set reponse headers and values.
    resp['Cache-Control'] = 'public,max-age=100000'
    resp['Vary'] = 'Accept-Encoding'
    return resp

def dept_list(request):
    ......
    # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
    return render(request, 'dept_emp/dept_list.html',
                  {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
9 có giá trị 'A' (có sẵn) trong trường trạng thái. Bạn có thể tìm thêm thông tin về cách truy cập dữ liệu mô hình trong Hướng dẫn hướng dẫn trước đây của chúng tôi Phần 3: Sử dụng Mô hình> Tìm kiếm hồ sơ.

Ở cuối hàm xem, chúng tôi gọi hàm

def login_account(request):
    
    # the HttpResponseRedirect class return a HttpResponse object also, and the response is a redirect response which will change the web browser url.
    response = HttpResponseRedirect('/user/login_success/')
    
    # set cookie to transfer user name to login success page.
    response.set_cookie('user_name', user_name, 3600)
    
    return response
4 để tạo trang HTML và trả về trang dưới dạng phản hồi. Chức năng phím tắt này bao gồm một số chức năng khác để đơn giản hóa một trường hợp sử dụng rất phổ biến. Hàm
def login_account(request):
    
    # the HttpResponseRedirect class return a HttpResponse object also, and the response is a redirect response which will change the web browser url.
    response = HttpResponseRedirect('/user/login_success/')
    
    # set cookie to transfer user name to login success page.
    response.set_cookie('user_name', user_name, 3600)
    
    return response
4 chấp nhận các tham số sau:

  • Đối tượng
    def login_account(request):
        
        # the HttpResponseRedirect class return a HttpResponse object also, and the response is a redirect response which will change the web browser url.
        response = HttpResponseRedirect('/user/login_success/')
        
        # set cookie to transfer user name to login success page.
        response.set_cookie('user_name', user_name, 3600)
        
        return response
    6 ban đầu, là một
    def login_account(request):
        
        # the HttpResponseRedirect class return a HttpResponse object also, and the response is a redirect response which will change the web browser url.
        response = HttpResponseRedirect('/user/login_success/')
        
        # set cookie to transfer user name to login success page.
        response.set_cookie('user_name', user_name, 3600)
        
        return response
    7.
  • Một mẫu HTML với trình giữ chỗ cho dữ liệu.
  • Một biến
    def login_account(request):
        
        # the HttpResponseRedirect class return a HttpResponse object also, and the response is a redirect response which will change the web browser url.
        response = HttpResponseRedirect('/user/login_success/')
        
        # set cookie to transfer user name to login success page.
        response.set_cookie('user_name', user_name, 3600)
        
        return response
    8, là một từ điển Python, chứa dữ liệu để chèn vào giữ chỗ.

Chúng ta sẽ nói thêm về các mẫu và biến

def login_account(request):
    
    # the HttpResponseRedirect class return a HttpResponse object also, and the response is a redirect response which will change the web browser url.
    response = HttpResponseRedirect('/user/login_success/')
    
    # set cookie to transfer user name to login success page.
    response.set_cookie('user_name', user_name, 3600)
    
    return response
8 trong phần tiếp theo. Hãy để tạo mẫu của chúng tôi để chúng tôi thực sự có thể hiển thị một cái gì đó cho người dùng!

Mẫu

Mẫu là một tệp văn bản xác định cấu trúc hoặc bố cục của một tệp (chẳng hạn như trang HTML), nó sử dụng trình giữ chỗ để biểu diễn nội dung thực tế.

Một ứng dụng Django được tạo bằng StartApp (như bộ xương của ví dụ này) sẽ tìm kiếm các mẫu trong một thư mục con có tên 'Mẫu' của các ứng dụng của bạn. Ví dụ: trong chế độ xem chỉ mục mà chúng tôi vừa thêm vào, chức năng

def login_account(request):
    
    # the HttpResponseRedirect class return a HttpResponse object also, and the response is a redirect response which will change the web browser url.
    response = HttpResponseRedirect('/user/login_success/')
    
    # set cookie to transfer user name to login success page.
    response.set_cookie('user_name', user_name, 3600)
    
    return response
4 sẽ mong đợi tìm thấy tệp index.html in/locall Library/catalog/mẫu/và sẽ gây ra lỗi nếu không có tệp.startapp (like the skeleton of this example) will look for templates in a subdirectory named 'templates' of your applications. For example, in the index view that we just added, the
def login_account(request):
    
    # the HttpResponseRedirect class return a HttpResponse object also, and the response is a redirect response which will change the web browser url.
    response = HttpResponseRedirect('/user/login_success/')
    
    # set cookie to transfer user name to login success page.
    response.set_cookie('user_name', user_name, 3600)
    
    return response
4 function will expect to find the file index.html in /locallibrary/catalog/templates/ and will raise an error if the file is not present.

Bạn có thể kiểm tra điều này bằng cách lưu các thay đổi trước đó và truy cập

urlpatterns += [
    path('catalog/', include('catalog.urls')),
]
1 trong trình duyệt của mình - nó sẽ hiển thị thông báo lỗi khá trực quan: "
urlpatterns += [
    path('catalog/', include('catalog.urls')),
]
2" và các chi tiết khác.

Lưu ý: Dựa trên tệp cài đặt của dự án, Django sẽ tìm kiếm các mẫu ở một số nơi, tìm kiếm trong các ứng dụng đã cài đặt của bạn theo mặc định. Bạn có thể tìm hiểu thêm về cách Django tìm thấy các mẫu và mẫu nào mà nó hỗ trợ trong phần Mẫu của tài liệu Django. Based on your project's settings file, Django will look for templates in a number of places, searching in your installed applications by default. You can find out more about how Django finds templates and what template formats it supports in the Templates section of the Django documentation.

Mở rộng các mẫu

Mẫu chỉ mục sẽ cần đánh dấu HTML tiêu chuẩn cho đầu và cơ thể, cùng với các phần điều hướng để liên kết đến các trang khác của trang web (mà chúng tôi chưa tạo) và với các phần hiển thị dữ liệu văn bản và sách giới thiệu.

Phần lớn cấu trúc HTML và điều hướng sẽ giống nhau trong mỗi trang của trang web của chúng tôi. Thay vì sao chép mã nồi hơi trên mỗi trang, bạn có thể sử dụng ngôn ngữ khuôn mẫu Django để khai báo một mẫu cơ sở, sau đó mở rộng nó để thay thế các bit khác nhau cho mỗi trang cụ thể.

Đoạn mã sau là mẫu cơ sở mẫu từ tệp base_generic.html. Chúng tôi sẽ sớm tạo mẫu cho locall Library. Mẫu dưới đây bao gồm HTML phổ biến với các phần cho một tiêu đề, thanh bên và nội dung chính được đánh dấu bằng thẻ mẫu

urlpatterns += [
    path('catalog/', include('catalog.urls')),
]
3 và
urlpatterns += [
    path('catalog/', include('catalog.urls')),
]
4. Bạn có thể để trống các khối hoặc bao gồm nội dung mặc định để sử dụng khi kết xuất các trang xuất phát từ mẫu.base_generic.html file. We'll be creating the template for LocalLibrary shortly. The sample below includes common HTML with sections for a title, a sidebar, and main contents marked with the named
urlpatterns += [
    path('catalog/', include('catalog.urls')),
]
3 and
urlpatterns += [
    path('catalog/', include('catalog.urls')),
]
4 template tags. You can leave the blocks empty, or include default content to use when rendering pages derived from the template.

Lưu ý: Thẻ mẫu là các hàm mà bạn có thể sử dụng trong một mẫu để lặp qua danh sách, thực hiện các hoạt động có điều kiện dựa trên giá trị của một biến, v.v. Ngoài các thẻ mẫu, cú pháp mẫu cho phép bạn tham chiếu các biến được truyền vào mẫu từ chế độ xem và sử dụng các bộ lọc mẫu để định dạng các biến (ví dụ: để chuyển đổi chuỗi thành chữ thường). Template tags are functions that you can use in a template to loop through lists, perform conditional operations based on the value of a variable, and so on. In addition to template tags, the template syntax allows you to reference variables that are passed into the template from the view, and use template filters to format variables (for example, to convert a string to lower case).

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('about/',views.aboutview),
    path('',views.homeview),
]
1

Khi xác định một mẫu cho một chế độ xem cụ thể, trước tiên chúng tôi chỉ định mẫu cơ sở bằng thẻ mẫu

urlpatterns += [
    path('catalog/', include('catalog.urls')),
]
5 - xem mẫu mã bên dưới. Sau đó, chúng tôi khai báo những phần nào từ mẫu chúng tôi muốn thay thế (nếu có), sử dụng ________ 63/________ 64 Phần như trong mẫu cơ sở.

Ví dụ: đoạn mã bên dưới cho thấy cách sử dụng thẻ mẫu

urlpatterns += [
    path('catalog/', include('catalog.urls')),
]
5 và ghi đè khối
urlpatterns += [
    path('catalog/', include('catalog.urls')),
]
9. HTML được tạo sẽ bao gồm mã và cấu trúc được xác định trong mẫu cơ sở, bao gồm nội dung mặc định mà bạn đã xác định trong khối
urlpatterns = [
    path('', views.index, name='index'),
]
0, nhưng khối
urlpatterns += [
    path('catalog/', include('catalog.urls')),
]
9 mới thay cho trang web mặc định.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('about/',views.aboutview),
    path('',views.homeview),
]
2

Mẫu cơ sở locall Library

Chúng tôi sẽ sử dụng đoạn mã sau làm mẫu cơ sở cho trang web locall Library. Như bạn có thể thấy, nó chứa một số mã HTML và xác định các khối cho

urlpatterns = [
    path('', views.index, name='index'),
]
0,
urlpatterns = [
    path('', views.index, name='index'),
]
3 và
urlpatterns += [
    path('catalog/', include('catalog.urls')),
]
9. Chúng tôi có một tiêu đề mặc định và một thanh bên mặc định với các liên kết đến danh sách tất cả các cuốn sách và tác giả, cả hai được đặt trong các khối để dễ dàng thay đổi trong tương lai.

Lưu ý: Chúng tôi cũng giới thiệu hai thẻ mẫu bổ sung:

urlpatterns = [
    path('', views.index, name='index'),
]
5 và
urlpatterns = [
    path('', views.index, name='index'),
]
6. Các thẻ này sẽ được giải thích trong các phần sau.
We also introduce two additional template tags:
urlpatterns = [
    path('', views.index, name='index'),
]
5 and
urlpatterns = [
    path('', views.index, name='index'),
]
6. These tags will be explained in following sections.

Tạo một tệp mới Base_Generic.html in/locall Library/Catalog/Mẫu/và dán mã sau vào tệp:base_generic.html in /locallibrary/catalog/templates/ and paste the following code to the file:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('about/',views.aboutview),
    path('',views.homeview),
]
3

Mẫu bao gồm CSS từ Bootstrap để cải thiện bố cục và trình bày của trang HTML. Sử dụng Bootstrap (hoặc khung web phía máy khách khác) là một cách nhanh chóng để tạo một trang hấp dẫn hiển thị tốt trên các kích thước màn hình khác nhau.

Mẫu cơ sở cũng tham chiếu một tệp CSS cục bộ (styles.css) cung cấp kiểu dáng bổ sung. Tạo tệp styles.css trong/locall Library/catalog/static/css/và dán mã sau trong tệp:styles.css) that provides additional styling. Create a styles.css file in /locallibrary/catalog/static/css/ and paste the following code in the file:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('about/',views.aboutview),
    path('',views.homeview),
]
4

Mẫu chỉ mục

Tạo một tệp HTML mới INDEX.html in/locall Library/Catalog/Mẫu/và dán mã sau trong tệp. Mã này mở rộng mẫu cơ sở của chúng tôi trên dòng đầu tiên và sau đó thay thế khối

urlpatterns += [
    path('catalog/', include('catalog.urls')),
]
9 mặc định cho mẫu.index.html in /locallibrary/catalog/templates/ and paste the following code in the file. This code extends our base template on the first line, and then replaces the default
urlpatterns += [
    path('catalog/', include('catalog.urls')),
]
9 block for the template.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('about/',views.aboutview),
    path('',views.homeview),
]
5

Trong phần Nội dung động, chúng tôi khai báo các trình giữ chỗ (biến mẫu) cho thông tin từ chế độ xem mà chúng tôi muốn bao gồm. Các biến được đặt với nẹp đôi (tay lái).

Lưu ý: Bạn có thể dễ dàng nhận ra các biến mẫu và thẻ mẫu (hàm) - các biến được đặt trong niềng răng đôi (

urlpatterns = [
    path('', views.index, name='index'),
]
8) và các thẻ được đặt trong niềng răng đơn với các dấu hiệu phần trăm (
urlpatterns = [
    path('', views.index, name='index'),
]
9).
You can easily recognize template variables and template tags (functions) - variables are enclosed in double braces (
urlpatterns = [
    path('', views.index, name='index'),
]
8), and tags are enclosed in single braces with percentage signs (
urlpatterns = [
    path('', views.index, name='index'),
]
9).

Điều quan trọng cần lưu ý ở đây là các biến được đặt tên với các khóa mà chúng tôi chuyển vào từ điển

def login_account(request):
    
    # the HttpResponseRedirect class return a HttpResponse object also, and the response is a redirect response which will change the web browser url.
    response = HttpResponseRedirect('/user/login_success/')
    
    # set cookie to transfer user name to login success page.
    response.set_cookie('user_name', user_name, 3600)
    
    return response
8 trong hàm
def login_account(request):
    
    # the HttpResponseRedirect class return a HttpResponse object also, and the response is a redirect response which will change the web browser url.
    response = HttpResponseRedirect('/user/login_success/')
    
    # set cookie to transfer user name to login success page.
    response.set_cookie('user_name', user_name, 3600)
    
    return response
4 của chế độ xem của chúng tôi (xem mẫu bên dưới). Các biến sẽ được thay thế bằng các giá trị liên quan của chúng khi mẫu được hiển thị.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('about/',views.aboutview),
    path('',views.homeview),
]
6

Tham khảo các tệp tĩnh trong các mẫu

Dự án của bạn có khả năng sử dụng tài nguyên tĩnh, bao gồm JavaScript, CSS và hình ảnh. Vì vị trí của các tệp này có thể không được biết (hoặc có thể thay đổi), Django cho phép bạn chỉ định vị trí trong các mẫu của bạn so với cài đặt toàn cầu

<a href="{% url 'index' %}">Homea>.
2. Trang web bộ xương mặc định đặt giá trị của
<a href="{% url 'index' %}">Homea>.
2 thành '
<a href="{% url 'index' %}">Homea>.
4', nhưng bạn có thể chọn lưu trữ chúng trên mạng phân phối nội dung hoặc ở nơi khác.

Trong mẫu trước tiên bạn gọi thẻ mẫu

<a href="{% url 'index' %}">Homea>.
5 chỉ định "tĩnh" để thêm thư viện mẫu, như được hiển thị trong mẫu mã bên dưới. Sau đó, bạn có thể sử dụng thẻ mẫu
<a href="{% url 'index' %}">Homea>.
6 và chỉ định URL tương đối vào tệp cần thiết.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('about/',views.aboutview),
    path('',views.homeview),
]
7

Bạn có thể thêm một hình ảnh vào trang theo cách tương tự, ví dụ:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('about/',views.aboutview),
    path('',views.homeview),
]
8

Lưu ý: Các mẫu trên chỉ định vị trí của các tệp, nhưng Django không phục vụ chúng theo mặc định. Chúng tôi đã cấu hình máy chủ web phát triển để phục vụ các tệp bằng cách sửa đổi bản đồ URL toàn cầu (/locall Library/locall Library/urls.py) khi chúng tôi tạo bộ xương trang web, nhưng vẫn cần bật tệp phục vụ trong sản xuất. Chúng tôi sẽ xem xét điều này sau. The samples above specify where the files are located, but Django does not serve them by default. We configured the development web server to serve files by modifying the global URL mapper (/locallibrary/locallibrary/urls.py) when we created the website skeleton, but still need to enable file serving in production. We'll look at this later.

Để biết thêm thông tin về việc làm việc với các tệp tĩnh, hãy xem Quản lý các tệp tĩnh trong tài liệu Django.

Liên kết với URL

Mẫu cơ sở ở trên đã giới thiệu thẻ mẫu

urlpatterns = [
    path('', views.index, name='index'),
]
5.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('about/',views.aboutview),
    path('',views.homeview),
]
9

Thẻ này chấp nhận tên của hàm

def home_page(request):
    # invoke render shortcut to create HttpResponse object with template html file.
    resp = render(request, 'dept_emp/home_page.html')

    # set reponse headers and values.
    resp['Cache-Control'] = 'public,max-age=100000'
    resp['Vary'] = 'Accept-Encoding'
    return resp

def dept_list(request):
    ......
    # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files.
    return render(request, 'dept_emp/dept_list.html',
                  {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
0 được gọi trong url.py của bạn và các giá trị cho bất kỳ đối số nào mà chế độ xem liên quan sẽ nhận được từ hàm đó và trả về URL mà bạn có thể sử dụng để liên kết với tài nguyên.urls.py and the values for any arguments that the associated view will receive from that function, and returns a URL that you can use to link to the resource.

Định cấu hình nơi tìm các mẫu

Vị trí nơi Django tìm kiếm các mẫu được chỉ định trong đối tượng

<a href="{% url 'index' %}">Homea>.
9 trong tệp seteds.py. Cài đặt mặc định.py (như được tạo cho hướng dẫn này) trông giống như thế này:settings.py file. The default settings.py (as created for this tutorial) looks something like this:

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

def aboutview(request):
  return render(request,"home.html")
def homeview(request):
  return render(request,"about.html")
0

Cài đặt của

from django.shortcuts import render

# Create your views here.
0, là quan trọng nhất, vì nó bảo Django tìm kiếm các mẫu trong một thư mục của mỗi ứng dụng trong dự án, được đặt tên là "Mẫu" (điều này giúp nhóm các mẫu dễ dàng hơn với ứng dụng liên quan của họ để dễ dàng sử dụng lại) .

Chúng tôi cũng có thể chỉ định các vị trí cụ thể cho Django để tìm kiếm các thư mục bằng cách sử dụng

from django.shortcuts import render

# Create your views here.
1 (nhưng điều đó chưa cần thiết).

Nó trông như thế nào?

Tại thời điểm này, chúng tôi đã tạo tất cả các tài nguyên cần thiết để hiển thị trang chỉ mục. Chạy máy chủ (

from django.shortcuts import render

# Create your views here.
2) và mở
from django.shortcuts import render

# Create your views here.
3 trong trình duyệt của bạn. Nếu mọi thứ được cấu hình chính xác, trang web của bạn sẽ trông giống như ảnh chụp màn hình sau.

Hướng dẫn how do i return an html file in django? - làm cách nào để trả lại tệp html trong django?

Lưu ý: Tất cả các cuốn sách và tất cả các liên kết của tác giả sẽ không hoạt động vì các đường dẫn, chế độ xem và mẫu cho các trang đó không được xác định. Chúng tôi chỉ cần chèn giữ chỗ cho các liên kết đó trong mẫu

from django.shortcuts import render

# Create your views here.
4. The All books and All authors links will not work yet because the paths, views, and templates for those pages are not defined. We just inserted placeholders for those links in the
from django.shortcuts import render

# Create your views here.
4 template.

Thử thách bản thân

Dưới đây là một vài nhiệm vụ để kiểm tra sự quen thuộc của bạn với các truy vấn, chế độ xem và mẫu mô hình.

  1. Mẫu cơ sở locall Library bao gồm một khối
    urlpatterns = [
        path('', views.index, name='index'),
    ]
    
    0. Ghi đè khối này trong mẫu chỉ mục và tạo một tiêu đề mới cho trang.

    Lưu ý: Phần mở rộng các mẫu giải thích cách tạo các khối và mở rộng một khối trong một mẫu khác. The section Extending templates explains how to create blocks and extend a block in another template.

  2. Sửa đổi chế độ xem để tạo số lượng cho các thể loại và sách có chứa một từ cụ thể (trường hợp không nhạy cảm) và chuyển kết quả cho
    def login_account(request):
        
        # the HttpResponseRedirect class return a HttpResponse object also, and the response is a redirect response which will change the web browser url.
        response = HttpResponseRedirect('/user/login_success/')
        
        # set cookie to transfer user name to login success page.
        response.set_cookie('user_name', user_name, 3600)
        
        return response
    8. Bạn hoàn thành điều này theo cách tương tự như tạo và sử dụng
    from django.shortcuts import render
    
    # Create your views here.
    
    7 và
    from django.shortcuts import render
    
    # Create your views here.
    
    8. Sau đó cập nhật mẫu chỉ mục để bao gồm các biến này.

Bản tóm tắt

Chúng tôi vừa tạo trang chủ cho trang web của chúng tôi-một trang HTML hiển thị một số bản ghi từ cơ sở dữ liệu và liên kết đến các trang chưa được tạo khác. Trên đường đi, chúng tôi đã học thông tin cơ bản về người lập bản đồ URL, chế độ xem, truy vấn cơ sở dữ liệu với các mô hình, chuyển thông tin đến một mẫu từ chế độ xem và tạo và mở rộng các mẫu.

Trong bài viết tiếp theo, chúng tôi sẽ xây dựng kiến ​​thức này để tạo bốn trang còn lại của trang web của chúng tôi.

Xem thêm

Trong mô -đun này

Có HTML trong Django không?

Nó có thể tạo ra bất kỳ định dạng dựa trên văn bản nào (HTML, XML, CSV, v.v.)..

Kết xuất trả lại trong django là gì?

Trong django, render () là một trong những hàm được sử dụng nhiều nhất kết hợp một mẫu với từ điển ngữ cảnh và trả về một đối tượng httpresponse với văn bản được hiển thị.returns an HttpResponse object with the rendered text.

Chức năng nào được sử dụng bởi các chế độ xem PY để hiển thị mẫu HTML?

Xem (dựa trên chức năng) Danh mục mở/chế độ xem.py và lưu ý rằng tệp đã nhập hàm tắt RENDER () để tạo tệp HTML bằng cách sử dụng mẫu và dữ liệu: từ Django.render() shortcut function to generate an HTML file using a template and data: from django.

{ % Bao gồm %} trong django là gì?

Thẻ bao gồm cho phép bạn bao gồm một mẫu bên trong mẫu hiện tại.Điều này rất hữu ích khi bạn có một khối nội dung giống nhau cho nhiều trang.allows you include a template inside the current template. This is useful when you have a block of content that are the same for many pages.