Hướng dẫn Django cho người mới bắt đầu (P4)

Sau 3 phần trước, chúng ta đến với phần 4 Hướng dẫn Django cho người mới bắt đầu. Đến với phần này, mình sẽ hướng dẫn các bạn thêm về chỉnh sửa views và urls.

Chỉnh sửa views:

  • Bây giờ chúng ta hãy thêm một vài views nữa vào polls/views.py:

    def detail(request, question_id):

        return HttpResponse("Look at question %s." % question_id)
    

    def results(request, question_id):

        response = "Look at the results of question %s."
    
        return HttpResponse(response % question_id)
    

    def vote(request, question_id):

        return HttpResponse("Voting question %s." % question_id)
    

Thực hiện như cũ, chuyển các views mới này vào polls/urls.py bằng các thêm các path:

from django.urls import path

from . import views

urlpatterns = [
    # ex: /polls/
    path('', views.index, name='index'),
    # ex: /polls/5/
    path('<int:question_id>/', views.detail, name='detail'),
    # ex: /polls/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),
]
Hãy load lại trang trên trình duyệt của bạn, nó sẽ chạy detail() và hiển thị bất kỳ ID nào bạn cung cấp trong URL. Khi ai đó yêu cầu một trang từ trang web của bạn - giả sử, “/ polls / 34 /”, Django sẽ tải mysite.urls mô-đun Python vì nó được ROOT_URLCONF cài đặt trỏ đến.

Bây giờ bạn có thể tiếp tục viết các views với chức năng nhất định. Ở đây bạn có thể tạo hiển thị 5 câu hỏi thăm dò mới nhất nằm trong hệ thống và sẽ được được phân cách bằng dấu phẩy và chia ra theo ngày xuất bản. Vào polls/views.py:

from django.http import HttpResponse

from .models import Question

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    output = ', '.join([q.question_text for q in latest_question_list])
    return HttpResponse(output)

# Giữ nguyên các views còn lại (chi tiết, kết quả, bình chọn)

Ở đây thiết kế giao diện của trang đã được định sẵn nếu bạn muốn thay đổi giao diện thì cần thực hiện tạo một thư mục gọi là templates trong polls. Trong thư mục templates hãy tạo thêm một thư mục khác là polls và trong polls tạo tệp index.html. Chính xác đường dẫn ở đây là polls/templates/polls/index.html. Sau đó bỏ đoạn mẫu dưới vào:

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

Bây giờ, hãy cập nhật indextrong polls/views.pyđể sử dụng mẫu":

from django.http import HttpResponse
from django.template import loader

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = {
        'latest_question_list': latest_question_list,
    }
    return HttpResponse(template.render(context, request))

Thao tác với URL

Khi chúng ta thực hiện liên kết đến một câu hỏi trong polls/index.html thì liên kết sẽ được mã hoá như sau:

<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
Nếu bạn muốn thay đổi URL của detail view chi tiết thành một cái gì đó khác, có thể thành một cái gì đó giống như polls/specifics/12/ thì bạn sẽ thay đổi nó trong polls/urls.py:
...
# added the word 'specifics'
path('specifics/<int:question_id>/', views.detail, name='detail'),
...

Để có thể dễ phân biết thì bạn có thể đặt tên cho các URL bằng cách thêm mục app_name vào trong polls/urls.py:

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
    path('<int:question_id>/results/', views.results, name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]
  • Sau đó thay đổi polls/index.html thành:
    <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

Xem lại phần 3 tại: Hướng dẫn Django cho người mới bắt đầu (P3)
Nguồn:django tutorial

Công nghệ được nhắc đến trong bài viết này

Tên Công NghệPhiên BảnPhát Hành
Django---
4 phút đọc·317 lượt xem·