Django模板操作

时间:2023-03-09 00:04:54
Django模板操作

进行加减运算

def index(request):
a = request.GET['a']
b = request.GET['b']
c = int(a) + int(b)
return HttpResponse(str(c))

Django模板操作

新建templates

新建home.html

<!DOCTYPE html>
<html>
<head>
<title>首页</title>
</head>
<body> <a href="/add?a=4&b=5">计算 4+5</a> </body>
</html>

编写views.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals # Create your views here. from django.http import HttpResponse
from django.shortcuts import render def index(request):
return render(request, 'home.html') def add(request):
a = request.GET['a']
b = request.GET['b']
c = int(a) + int(b)
return HttpResponse(str(c))

设置urls.py

"""dog URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from learn import views as learn_views # new urlpatterns = [
url(r'^$', learn_views.index, name='home'), # new
url(r'^add/$', learn_views.add, name='add'), # new
url(r'^admin/', admin.site.urls),
]

循环

def index(request):
tutorList = ['Html', 'css', 'jQuery', 'Python', 'Django']
return render(request, 'learn/home.html', {'tutorList': tutorList})
{% for i in tutorList %}
{{ i }}
{% endfor %}

字典

def index(request):
info_dict = {'site': u'我的站点', 'content': u'站点内容'}
return render(request, 'learn/home.html', {'info_dict': info_dict})
{{ info_dict.site }} - {{ info_dict.content }}