05.模板显示
django模板系统基本语法
变量标签:{{variable_name}}
for循环标签{%for x in list %},{% endfor %}
if-else标签{% if %},{%.else %},{% endif %}
举个栗子:
<ul>
{% for item in list %}
<li>{{item}</li>
{% endfor %}
</ul>
{% if true %}
<p>it is a true part</p>
{% else %}
<p>it is a false part</p>
{% endif %}
//设置template路径setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'userapp',
'learnproject' //设置app
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR/'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',
],
},
},
]
// 渲染视图 views.py
def renderIndex(request):
users = User.objects.all()
name=request.GET['geo']
return render(request, 'season1/index.html', {
'Users': users
})
def hello3(request,userid):
if request.method == 'GET':
//do_something()
elif request.method == 'POST':
//do_something_else()
name= request.GET['name']
user_list = User.objects.all()
peiqi = None
for user in user_list:
if int(user.uid) == userid:
peiqi = user
break
if peiqi == None:
return HttpResponse("你好呀,404")
return HttpResponse("你好呀,%s"%(peiqi.nick))
//urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', views.hello),
path('hello2/',views.hello_db),
path('/',views.renderIndex),
path('hello/<int:userid>',views.views.hello3)
]