django-02流程的一些Tips

一 前期准备事项

在做django工程之前需要做一些基础的准备工作

  • 新建项目

    django-admin startproject mysite
    
  • 新建app
    到mysite的目录下

    python manage.py startapp learn
    

现在我们可以看到的目录结构

  learn/
  ├── __init__.py
  ├── admin.py
  ├── models.py
  ├── tests.py
  └── views.py
  • 修改setting文件,注册模块

     INSTALLED_APPS = (
       'django.contrib.admin',
       'django.contrib.auth',
       'django.contrib.contenttypes',
       'django.contrib.sessions',
       'django.contrib.messages',
       'django.contrib.staticfiles',
       'learn',
     )
    
  • 定义简单视图

from django.http import HttpResponse


def index(request):
      return HttpResponse(u"欢迎光临 自强学堂!")
  • 编写视图的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),  # new
    url(r'^admin/', admin.site.urls),
]
  • 页面传参数的方式
    views的定义方式
def add2(request, a, b):
    c = int(a) + int(b)
    return HttpResponse(str(c))

访问页面url地址 http://127.0.0.1:8002/add/4/5/

  • 模板前后端传参
    视图函数
# -*- coding: utf-8 -*-
from django.shortcuts import render

def home(request):
    string = u"我在自强学堂学习Django,用它来建网站"
    return render(request, 'home.html', {'string': string})

模板的home.html

{{ string }}

  • 列表的循环传参
view.py
def home(request):
    TutorialList = ["HTML", "CSS", "jQuery", "Python", "Django"]
    return render(request, 'home.html', {'TutorialList': TutorialList})

home.html

{% for i in TutorialList %}
{{ i }}
{% endfor %}
  • 字典的传参
    views.py
def home(request):
    info_dict = {'site': u'自强学堂', 'content': u'各种IT技术教程'}
    return render(request, 'home.html', {'info_dict': info_dict})

home.html

站点:{{ info_dict.site }} 内容:{{ info_dict.content }}
{% for key, value in info_dict.items %}
    {{ key }}: {{ value }}
  {% endfor %}
  • 模板用if判断和循环
    views.py
def home(request):
    List = map(str, range(100))# 一个长度为100的 List
    return render(request, 'home.html', {'List': List})

home.html

{% for item in List %}
    {{ item }}, 
{% endfor %}

{% for item in List %}
    {{ item }}{% if not forloop.last %},{% endif %} 
{% endfor %}


  
    {% for athlete in athlete_list %}
  • {{ athlete.name }}
  • { % empty %}
  • 抱歉,列表为空
  • {% endfor %}
def add(request, a, b): c = int(a) + int(b) return HttpResponse(str(c)) # urls.py urlpatterns = patterns('', url(r'^add/(\d+)/(\d+)/$', 'app.views.add', name='add'), ) # template html {% url 'add' 4 5 %}

你可能感兴趣的:(django-02流程的一些Tips)