django添加新的web頁面流程

1.在應用的urls.py中定義新頁面的url請求地址##
polls/urls.py

path('', views.IndexView.as_view(), name='index'), 

path函數的第一個參數: url的路徑
path函數的第二個參數:views.IndexView.as_view() 顯示頁面調用的方法
path函數的第二個參數: name=‘index’ 是顯示頁面調用的方法的傳參
2.在應用的view.py 添加顯示頁面方法
polls/view.py

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from .models import Choice, Question
    class IndexView(generic.ListView):
        template_name = 'polls/index.html'
        context_object_name = 'latest_question_list'

這裏使用的是重載IndexView類
如果自定義的話使用下面的方法:

       // polls/urls.py
        path('', views.index, name='index'),
       // polls/urls.py      
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from .models import Choice, 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))

‘latest_question_list’: latest_question_list這一句是將html中的latest_question_list字符串替換成ptyhonlatest_question_list數據,ptyhonlatest_question_list可以是任何類型
…/polls/models.py

  from django.db import models
    from django.utils import timezone
    # Create your models here.
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
        def __str__(self):
            return self.question_text
    class Choice(models.Model):
        question = models.ForeignKey(Question, on_delete=models.CASCADE)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)
        def __str__(self):
            return self.choice_text

Question.objects.order_by(’-pub_date’)[:5]中:
Question.objects.order_by(’-pub_date’)獲取Question的所有信息,按照pub_date字段的信息排序
[:5]最後5條

3.編寫html模板文件

polls/templates/polls/index.html
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}">

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

latest_question_list:會自個替換成python的數據,這裏是一個數據庫相關的數據結構,使用for循環讀取裏面的數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章