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

  • 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.

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 run an html file in django? - làm cách nào để chạy một 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à:

  • urlpatterns = [
        path('', views.index, name='index'),
    ]
    
    5 - Trang Home (Index).
  • urlpatterns = [
        path('', views.index, name='index'),
    ]
    
    6 - Danh sách tất cả các cuốn sách.
  • urlpatterns = [
        path('', views.index, name='index'),
    ]
    
    7 - Danh sách tất cả các tác giả.
  • urlpatterns = [
        path('', views.index, name='index'),
    ]
    
    8 - Chế độ xem chi tiết cho một cuốn sách cụ thể, với khóa chính trường là
    urlpatterns = [
        path('', views.index, name='index'),
    ]
    
    9 (mặc định). Ví dụ: URL cho cuốn sách thứ ba được thêm vào danh sách sẽ là
    <a href="{% url 'index' %}">Home</a>.
    
    0.
  • <a href="{% url 'index' %}">Home</a>.
    
    1 - Chế độ xem chi tiết cho tác giả cụ thể với trường chính chính là
    urlpatterns = [
        path('', views.index, name='index'),
    ]
    
    9. Ví dụ: URL cho tác giả thứ 11 được thêm vào danh sách sẽ là
    <a href="{% url 'index' %}">Home</a>.
    
    3.

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

urlpatterns = [
    path('', views.index, name='index'),
]
9 ở 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ố

<a href="{% url 'index' %}">Home</a>.
5 trong URL, ví dụ
<a href="{% url 'index' %}">Home</a>.
6. 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
<a href="{% url 'index' %}">Home</a>.
5 parameters in the URL, for example
<a href="{% url 'index' %}">Home</a>.
6. 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 (

urlpatterns = [
    path('', views.index, name='index'),
]
5). 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

urlpatterns = [
    path('', views.index, name='index'),
]
5 được nhận, mô -đun URLConf
<a href="{% url 'index' %}">Home</a>.
9 sẽ xử lý chuỗi con còn lại.locallibrary/urls.py file to ensure that whenever a URL that starts with
urlpatterns = [
    path('', views.index, name='index'),
]
5 is received, the URLConf module
<a href="{% url 'index' %}">Home</a>.
9 will process the remaining substring.

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

<a href="{% url 'index' %}">Home</a>.
9:locallibrary/urls.py includes the
<a href="{% url 'index' %}">Home</a>.
9 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.shortcuts import render

# Create your views here.
1, 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.shortcuts import render

# Create your views here.
1, 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

from django.shortcuts import render

# Create your views here.
2 xác định như sau:

  • Một mẫu URL, là một chuỗi trống:
    from django.shortcuts import render
    
    # Create your views here.
    
    3. 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:
    from django.shortcuts import render
    
    # Create your views here.
    
    4, là hàm có tên
    from django.shortcuts import render
    
    # Create your views here.
    
    5 trong tệp Views.py.views.py file.

Hàm

from django.shortcuts import render

# Create your views here.
2 cũng chỉ định tham số
from django.shortcuts import render

# Create your views here.
7, đâ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' %}">Home</a>.

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

from django.shortcuts import render

# Create your views here.
8), 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
from django.shortcuts import render

# Create your views here.
9), 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
from django.shortcuts import render

# Create your views here.
8), but if we change the pattern for our home page, for example, to
from django.shortcuts import render

# Create your views here.
9) 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

from .models import Book, Author, BookInstance, Genre

def index(request):
    """View function for home page of site."""

    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    # Available books (status = 'a')
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()

    # The 'all()' is implied by default.
    num_authors = Author.objects.count()

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)
0,
from .models import Book, Author, BookInstance, Genre

def index(request):
    """View function for home page of site."""

    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    # Available books (status = 'a')
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()

    # The 'all()' is implied by default.
    num_authors = Author.objects.count()

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)
1, có sẵn
from .models import Book, Author, BookInstance, Genre

def index(request):
    """View function for home page of site."""

    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    # Available books (status = 'a')
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()

    # The 'all()' is implied by default.
    num_authors = Author.objects.count()

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)
1 và
from .models import Book, Author, BookInstance, Genre

def index(request):
    """View function for home page of site."""

    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    # Available books (status = 'a')
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()

    # The 'all()' is implied by default.
    num_authors = Author.objects.count()

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)
3 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 .models import Book, Author, BookInstance, Genre

def index(request):
    """View function for home page of site."""

    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    # Available books (status = 'a')
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()

    # The 'all()' is implied by default.
    num_authors = Author.objects.count()

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)

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

from .models import Book, Author, BookInstance, Genre

def index(request):
    """View function for home page of site."""

    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    # Available books (status = 'a')
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()

    # The 'all()' is implied by default.
    num_authors = Author.objects.count()

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)
4 trên các lớp mô hình. Nó cũng có một danh sách các đối tượng
from .models import Book, Author, BookInstance, Genre

def index(request):
    """View function for home page of site."""

    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    # Available books (status = 'a')
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()

    # The 'all()' is implied by default.
    num_authors = Author.objects.count()

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)
1 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

from .models import Book, Author, BookInstance, Genre

def index(request):
    """View function for home page of site."""

    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    # Available books (status = 'a')
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()

    # The 'all()' is implied by default.
    num_authors = Author.objects.count()

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)
6 để 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
from .models import Book, Author, BookInstance, Genre

def index(request):
    """View function for home page of site."""

    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    # Available books (status = 'a')
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()

    # The 'all()' is implied by default.
    num_authors = Author.objects.count()

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)
6 chấp nhận các tham số sau:

  • Đối tượng
    from .models import Book, Author, BookInstance, Genre
    
    def index(request):
        """View function for home page of site."""
    
        # Generate counts of some of the main objects
        num_books = Book.objects.all().count()
        num_instances = BookInstance.objects.all().count()
    
        # Available books (status = 'a')
        num_instances_available = BookInstance.objects.filter(status__exact='a').count()
    
        # The 'all()' is implied by default.
        num_authors = Author.objects.count()
    
        context = {
            'num_books': num_books,
            'num_instances': num_instances,
            'num_instances_available': num_instances_available,
            'num_authors': num_authors,
        }
    
        # Render the HTML template index.html with the data in the context variable
        return render(request, 'index.html', context=context)
    
    8 ban đầu, là một
    from .models import Book, Author, BookInstance, Genre
    
    def index(request):
        """View function for home page of site."""
    
        # Generate counts of some of the main objects
        num_books = Book.objects.all().count()
        num_instances = BookInstance.objects.all().count()
    
        # Available books (status = 'a')
        num_instances_available = BookInstance.objects.filter(status__exact='a').count()
    
        # The 'all()' is implied by default.
        num_authors = Author.objects.count()
    
        context = {
            'num_books': num_books,
            'num_instances': num_instances,
            'num_instances_available': num_instances_available,
            'num_authors': num_authors,
        }
    
        # Render the HTML template index.html with the data in the context variable
        return render(request, 'index.html', context=context)
    
    9.
  • Một mẫu HTML với trình giữ chỗ cho dữ liệu.
  • Một biến
    <!DOCTYPE html>
    <html lang="en">
    <head>
      {% block title %}<title>Local Library</title>{% endblock %}
    </head>
    <body>
      {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
      {% block content %}<!-- default content text (typically empty) -->{% endblock %}
    </body>
    </html>
    
    0, 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

<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
</head>
<body>
  {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
  {% block content %}<!-- default content text (typically empty) -->{% endblock %}
</body>
</html>
0 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, hàm

from .models import Book, Author, BookInstance, Genre

def index(request):
    """View function for home page of site."""

    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    # Available books (status = 'a')
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()

    # The 'all()' is implied by default.
    num_authors = Author.objects.count()

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)
6 sẽ mong đợi tìm thấy tệp index.html in/locall Library/catalog/mẫu/và sẽ gây 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
from .models import Book, Author, BookInstance, Genre

def index(request):
    """View function for home page of site."""

    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    # Available books (status = 'a')
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()

    # The 'all()' is implied by default.
    num_authors = Author.objects.count()

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)
6 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

<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
</head>
<body>
  {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
  {% block content %}<!-- default content text (typically empty) -->{% endblock %}
</body>
</html>
3 trong trình duyệt của bạn - nó sẽ hiển thị thông báo lỗi khá trực quan: "
<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
</head>
<body>
  {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
  {% block content %}<!-- default content text (typically empty) -->{% endblock %}
</body>
</html>
4" 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

<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
</head>
<body>
  {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
  {% block content %}<!-- default content text (typically empty) -->{% endblock %}
</body>
</html>
5 và
<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
</head>
<body>
  {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
  {% block content %}<!-- default content text (typically empty) -->{% endblock %}
</body>
</html>
6. 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
<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
</head>
<body>
  {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
  {% block content %}<!-- default content text (typically empty) -->{% endblock %}
</body>
</html>
5 and
<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
</head>
<body>
  {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
  {% block content %}<!-- default content text (typically empty) -->{% endblock %}
</body>
</html>
6 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).

<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
</head>
<body>
  {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
  {% block content %}<!-- default content text (typically empty) -->{% endblock %}
</body>
</html>

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

<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
</head>
<body>
  {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
  {% block content %}<!-- default content text (typically empty) -->{% endblock %}
</body>
</html>
7 - 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 ________ 55/________ 56 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

<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
</head>
<body>
  {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
  {% block content %}<!-- default content text (typically empty) -->{% endblock %}
</body>
</html>
7 và ghi đè khối
{% extends "base_generic.html" %}

{% block content %}
  <h2>Local Library Home</h2>
  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
{% endblock %}
1. 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
{% extends "base_generic.html" %}

{% block content %}
  <h2>Local Library Home</h2>
  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
{% endblock %}
2, nhưng khối
{% extends "base_generic.html" %}

{% block content %}
  <h2>Local Library Home</h2>
  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
{% endblock %}
1 mới thay cho trang web mặc định.

{% extends "base_generic.html" %}

{% block content %}
  <h2>Local Library Home</h2>
  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
{% endblock %}

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

{% extends "base_generic.html" %}

{% block content %}
  <h2>Local Library Home</h2>
  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
{% endblock %}
2,
{% extends "base_generic.html" %}

{% block content %}
  <h2>Local Library Home</h2>
  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
{% endblock %}
5 và
{% extends "base_generic.html" %}

{% block content %}
  <h2>Local Library Home</h2>
  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
{% endblock %}
1. 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:

{% extends "base_generic.html" %}

{% block content %}
  <h2>Local Library Home</h2>
  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
{% endblock %}
7 và
{% extends "base_generic.html" %}

{% block content %}
  <h2>Local Library Home</h2>
  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
{% endblock %}
8. Các thẻ này sẽ được giải thích trong các phần sau.
We also introduce two additional template tags:
{% extends "base_generic.html" %}

{% block content %}
  <h2>Local Library Home</h2>
  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
{% endblock %}
7 and
{% extends "base_generic.html" %}

{% block content %}
  <h2>Local Library Home</h2>
  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
{% endblock %}
8. 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:

<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm//dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <!-- Add additional CSS in static file -->
  {% load static %}
  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-2">
      {% block sidebar %}
        <ul class="sidebar-nav">
          <li><a href="{% url 'index' %}">Home</a></li>
          <li><a href="">All books</a></li>
          <li><a href="">All authors</a></li>
        </ul>
     {% endblock %}
      </div>
      <div class="col-sm-10 ">{% block content %}{% endblock %}</div>
    </div>
  </div>
</body>
</html>

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:

.sidebar-nav {
  margin-top: 20px;
  padding: 0;
  list-style: none;
}

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

{% extends "base_generic.html" %}

{% block content %}
  <h2>Local Library Home</h2>
  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
{% endblock %}
1 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
{% extends "base_generic.html" %}

{% block content %}
  <h2>Local Library Home</h2>
  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
{% endblock %}
1 block for the template.

{% extends "base_generic.html" %}

{% block content %}
  <h2>Local Library Home</h2>
  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
  <h2>Dynamic content</h2>
  <p>The library has the following record counts:</p>
  <ul>
    <li><strong>Books:</strong> {{ num_books }}</li>
    <li><strong>Copies:</strong> {{ num_instances }}</li>
    <li><strong>Copies available:</strong> {{ num_instances_available }}</li>
    <li><strong>Authors:</strong> {{ num_authors }}</li>
  </ul>
{% endblock %}

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 (

<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm//dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <!-- Add additional CSS in static file -->
  {% load static %}
  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-2">
      {% block sidebar %}
        <ul class="sidebar-nav">
          <li><a href="{% url 'index' %}">Home</a></li>
          <li><a href="">All books</a></li>
          <li><a href="">All authors</a></li>
        </ul>
     {% endblock %}
      </div>
      <div class="col-sm-10 ">{% block content %}{% endblock %}</div>
    </div>
  </div>
</body>
</html>
0) và các thẻ được đặt trong niềng răng đơn với các dấu hiệu phần trăm (
<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm//dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <!-- Add additional CSS in static file -->
  {% load static %}
  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-2">
      {% block sidebar %}
        <ul class="sidebar-nav">
          <li><a href="{% url 'index' %}">Home</a></li>
          <li><a href="">All books</a></li>
          <li><a href="">All authors</a></li>
        </ul>
     {% endblock %}
      </div>
      <div class="col-sm-10 ">{% block content %}{% endblock %}</div>
    </div>
  </div>
</body>
</html>
1).
You can easily recognize template variables and template tags (functions) - variables are enclosed in double braces (
<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm//dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <!-- Add additional CSS in static file -->
  {% load static %}
  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-2">
      {% block sidebar %}
        <ul class="sidebar-nav">
          <li><a href="{% url 'index' %}">Home</a></li>
          <li><a href="">All books</a></li>
          <li><a href="">All authors</a></li>
        </ul>
     {% endblock %}
      </div>
      <div class="col-sm-10 ">{% block content %}{% endblock %}</div>
    </div>
  </div>
</body>
</html>
0), and tags are enclosed in single braces with percentage signs (
<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm//dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <!-- Add additional CSS in static file -->
  {% load static %}
  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-2">
      {% block sidebar %}
        <ul class="sidebar-nav">
          <li><a href="{% url 'index' %}">Home</a></li>
          <li><a href="">All books</a></li>
          <li><a href="">All authors</a></li>
        </ul>
     {% endblock %}
      </div>
      <div class="col-sm-10 ">{% block content %}{% endblock %}</div>
    </div>
  </div>
</body>
</html>
1).

Đ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

<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
</head>
<body>
  {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
  {% block content %}<!-- default content text (typically empty) -->{% endblock %}
</body>
</html>
0 trong hàm
from .models import Book, Author, BookInstance, Genre

def index(request):
    """View function for home page of site."""

    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    # Available books (status = 'a')
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()

    # The 'all()' is implied by default.
    num_authors = Author.objects.count()

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)
6 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ị.

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

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

<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm//dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <!-- Add additional CSS in static file -->
  {% load static %}
  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-2">
      {% block sidebar %}
        <ul class="sidebar-nav">
          <li><a href="{% url 'index' %}">Home</a></li>
          <li><a href="">All books</a></li>
          <li><a href="">All authors</a></li>
        </ul>
     {% endblock %}
      </div>
      <div class="col-sm-10 ">{% block content %}{% endblock %}</div>
    </div>
  </div>
</body>
</html>
4. Trang web bộ xương mặc định đặt giá trị của
<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm//dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <!-- Add additional CSS in static file -->
  {% load static %}
  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-2">
      {% block sidebar %}
        <ul class="sidebar-nav">
          <li><a href="{% url 'index' %}">Home</a></li>
          <li><a href="">All books</a></li>
          <li><a href="">All authors</a></li>
        </ul>
     {% endblock %}
      </div>
      <div class="col-sm-10 ">{% block content %}{% endblock %}</div>
    </div>
  </div>
</body>
</html>
4 thành '
<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm//dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <!-- Add additional CSS in static file -->
  {% load static %}
  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-2">
      {% block sidebar %}
        <ul class="sidebar-nav">
          <li><a href="{% url 'index' %}">Home</a></li>
          <li><a href="">All books</a></li>
          <li><a href="">All authors</a></li>
        </ul>
     {% endblock %}
      </div>
      <div class="col-sm-10 ">{% block content %}{% endblock %}</div>
    </div>
  </div>
</body>
</html>
6', 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

<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm//dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <!-- Add additional CSS in static file -->
  {% load static %}
  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-2">
      {% block sidebar %}
        <ul class="sidebar-nav">
          <li><a href="{% url 'index' %}">Home</a></li>
          <li><a href="">All books</a></li>
          <li><a href="">All authors</a></li>
        </ul>
     {% endblock %}
      </div>
      <div class="col-sm-10 ">{% block content %}{% endblock %}</div>
    </div>
  </div>
</body>
</html>
7 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
<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm//dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <!-- Add additional CSS in static file -->
  {% load static %}
  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-2">
      {% block sidebar %}
        <ul class="sidebar-nav">
          <li><a href="{% url 'index' %}">Home</a></li>
          <li><a href="">All books</a></li>
          <li><a href="">All authors</a></li>
        </ul>
     {% endblock %}
      </div>
      <div class="col-sm-10 ">{% block content %}{% endblock %}</div>
    </div>
  </div>
</body>
</html>
8 và chỉ định URL tương đối vào tệp cần thiết.

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

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

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

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

{% extends "base_generic.html" %}

{% block content %}
  <h2>Local Library Home</h2>
  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
{% endblock %}
7.

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

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

from django.shortcuts import render

# Create your views here.
2 đượ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

.sidebar-nav {
  margin-top: 20px;
  padding: 0;
  list-style: none;
}
1 trong tệp setelfs.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:

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

Cài đặt của

.sidebar-nav {
  margin-top: 20px;
  padding: 0;
  list-style: none;
}
2, 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

.sidebar-nav {
  margin-top: 20px;
  padding: 0;
  list-style: none;
}
3 (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ủ (

.sidebar-nav {
  margin-top: 20px;
  padding: 0;
  list-style: none;
}
4) và mở
.sidebar-nav {
  margin-top: 20px;
  padding: 0;
  list-style: none;
}
5 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 run an html file in django? - làm cách nào để chạy một 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

.sidebar-nav {
  margin-top: 20px;
  padding: 0;
  list-style: none;
}
6. 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
.sidebar-nav {
  margin-top: 20px;
  padding: 0;
  list-style: none;
}
6 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
    {% extends "base_generic.html" %}
    
    {% block content %}
      <h2>Local Library Home</h2>
      <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
    {% endblock %}
    
    2. 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
    <!DOCTYPE html>
    <html lang="en">
    <head>
      {% block title %}<title>Local Library</title>{% endblock %}
    </head>
    <body>
      {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
      {% block content %}<!-- default content text (typically empty) -->{% endblock %}
    </body>
    </html>
    
    0. Bạn hoàn thành điều này theo cách tương tự như tạo và sử dụng
    .sidebar-nav {
      margin-top: 20px;
      padding: 0;
      list-style: none;
    }
    
    9 và
    {% extends "base_generic.html" %}
    
    {% block content %}
      <h2>Local Library Home</h2>
      <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
      <h2>Dynamic content</h2>
      <p>The library has the following record counts:</p>
      <ul>
        <li><strong>Books:</strong> {{ num_books }}</li>
        <li><strong>Copies:</strong> {{ num_instances }}</li>
        <li><strong>Copies available:</strong> {{ num_instances_available }}</li>
        <li><strong>Authors:</strong> {{ num_authors }}</li>
      </ul>
    {% endblock %}
    
    0. 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

Bạn có thể sử dụng HTML với Django không?

Bạn có thể sử dụng các mẫu Django trong HTML (đầy đủ hoặc một phần), văn bản, XML, JSON hoặc gần như bất kỳ định dạng dựa trên văn bản nào khác..

Cách sử dụng phản hồi HTML kết xuất nào trong Django?

Tạo chế độ xem trong chế độ xem.Py 2. Tạo một tệp mẫu sẽ được hiển thị và liên kết nó với chế độ xem.3. Tạo một URL để ánh xạ đến chế độ xem đó. 2. Create a template file which is to be rendered and link it to the view. 3. Create a URL to map to that view.

Bạn có thể sử dụng Django với HTML và CSS không?

Bạn có thể kết nối nó.Django là một khung phụ trợ, tất cả những gì nó làm trong frontend là dữ liệu in.Đọc về các mẫu trong Django.Các mẫu về cơ bản là các tệp HTML có nội dung động.. Django is a backend framework, all it does in the frontend is print data. Read about templates in Django. Templates are basically html files with dynamic content.

Làm cách nào để trả lại một tệp HTML trong Django?

Cách trả về tệp HTML dưới dạng phản hồi xem Django..
Trả về đối tượng httpresponse được tạo bởi lớp django.http.httpresponse.....
Trả về đối tượng httpresponse được tạo bởi lối tắt kết xuất.....
Trả về đối tượng httpresponse được tạo bởi django.http.httplesponseredirect lớp ..