Djanog

全局变量

老版本的 Django

    TEMPLATE_DIRS = (
        os.path.join(BASE_DIR, 'iaasms/render/templates'),
    )
    TEMPLATE_CONTEXT_PROCESSORS= (
        'django.contrib.auth.context_processors.auth',
        # 'django.core.context_processors.debug',
        # 'django.contrib.messages.context_processors.messages',
        'iaasms.context_processors.template_variable', # 自定义
    )

新版本的 Django

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

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' #模板中可以使用{{request.session.*}}


Paginator

Django分页
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render

def listing(request):
    contact_list = Contacts.objects.all()  # 获取所有contacts,假设在models.py中已定义了Contacts模型
    paginator = Paginator(contact_list, 25) # 每页25条

    page = request.GET.get('page')
    try:
        contacts = paginator.page(page) # contacts为Page对象!
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)

    return render(request, 'list.html', {'contacts': contacts})

猜你喜欢

转载自blog.csdn.net/qq_15551663/article/details/88841497