485   Django Python

前几篇文章只说了后台admin,现在该说说前端页面啦;

 

1,首先,添加一些页面方法的路由设置

$ vim polls/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    # ex: /polls/
    url(r'^$', views.index, name='index')
]

 

 

2,页面生成的方法

 

$ vim polls/views.py

from django.shortcuts import render

from .models import Question


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

 

 

3,具体页面内容,注意页面保存路径

$ vim polls/templates/polls/index.html
{% 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 %}

 

 

以上是生成一个html页面的整体流程,这些流程还有很多优化地方

1,url使用和命名空间
app_name 设置路由命名空间

$ vim polls/urls.py
from django.conf.urls import url

from . import views

app_name = 'polls'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(?P[0-9]+)/$', views.detail, name='detail')
]

 

在页面中使用url方法生成路径

$ vim polls/templates/polls/index.html
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

 

2,404异常捕捉等使用框架提供的异常捕捉方法获取数据

$ vim polls/views.py
from django.shortcuts import get_object_or_404, render

from .models import Question
# ...
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

 

上面页面生成方法其实已经被Django框架优化和集成了,便于减少重复代码

1,在路由设置使用框架默认页面生成方法as_view()

$ vim polls/urls.py
from django.conf.urls import url

from . import views

app_name = 'polls'
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P[0-9]+)/$', views.DetailView.as_view(), name='detail'),
    url(r'^(?P[0-9]+)/results/$', views.ResultsView.as_view(), name='results')
]

 

2,具体页面生成方法只需配置简单的

$ vim polls/views.py
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
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'

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by('-pub_date')[:5]


class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'


class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'




Leave a Reply

Your email address will not be published. Required fields are marked *