Workflow for Django

Workflow for Django

Github

  • add / create / clone repo
  • add / commit
  • sync
  • revert

虚拟环境

  • mkvirtualenv project_name
  • rmvirtualenv project_name
  • setvirtualenvproject project_name PATH
  • workon project_name
  • deactive

Start Project

  • django-admin.py startproject project_name
  • python manage.py migrate
  • python manage.py runserver

Start App

1. Start App

python manage.py startapp app_name

2. 修改 settings.py

project_namesettings.py文件中,找到INSTALLED_APPS列表,在列表的最后面增加 app_name

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app_name',
]

3. 创建视图

app_name目录内的views.py文件中,删除注释# Create your views here.,创建视图

def index(request):
    context_dict = {'boldmessage': "I am bold font from the context"}
    return render(request, 'rango/index.html', context_dict)

4. 应用 URL 映射

app_name目录中,创建一个叫做urls.py的文件。

from django.conf.urls import patterns, url
from rango import views

urlpatterns = [
        url(r'^$', views.index, name='index')]

5. 项目 URL 映射

project_name/project_name/urls.py中,更新urlpatterns列表。

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^app_name/', include('app_name.urls'))  # for example
]

使用模板

1. 创建目录

project_name/创建一个templates目录,在这个目录中为每一个 app 建立一个目录,例如 project_name/templates/app_name,用来存放app_name应用下的模板

2. 在 settings.py 中设置

setting.py中创建TEMPLATE_PATH变量,用它来储存 templates 目录。这里我们使用os.path.join()函数。

TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATE_DIRS = [
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    TEMPLATE_PATH,
]

3. 添加模板

template/app_name/目录里建立一个叫做index.html的文件,在新文件里加入下面代码:

<!DOCTYPE html>
<html>

    <head>
        <title>App</title>
    </head>

    <body>
        <h1>App says...</h1>
        hello world! <strong>{{ boldmessage }}</strong><br />
        <a href="/app_name/about/">About</a><br />
    </body>

</html>

4. 在 views.py 中 render

from django.shortcuts import render


def index(request):

    # Construct a dictionary to pass to the template engine as its context.
    # Note the key boldmessage is the same as {{ boldmessage }} in the template!
    context_dict = {'boldmessage': "I am bold font from the context"}

    # Return a rendered response to send to the client.
    # We make use of the shortcut function to make our lives easier.
    # Note that the first parameter is the template we wish to use.

    return render(request, 'rango/index.html', context_dict)

使用静态资源

1. 设置静态目录

settings.py文件,我们需要更新两个变量STATIC_URLSTATICFILES_DIRS元组,像下面一样创建一个储存静态目录(STATIC_PATH)的变量。

STATIC_PATH = os.path.join(BASE_DIR,'static')

STATIC_URL = '/static/' # You may find this is already defined as such.

STATICFILES_DIRS = [
    STATIC_PATH,
]

2. 使用静态资源

<!DOCTYPE html>

{% load static %} <!-- New line -->

<html>

    <head>
        <title>Rango</title>
    </head>

    <body>
        <h1>App says...</h1>
        hello world! <strong>{{ boldmessage }}</strong><br />
        <a href="/app_name/about/">About</a><br />
        <img src="{% static "images/appp.jpg" %}" alt="Picture of App" /> <!-- New line -->
    </body>

</html>

创建模型

1. 数据库设置

settings.py里添加一个叫做DATABASES的字典

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

2. 模型创建

class Category(models.Model):
    name = models.CharField(max_length=128, unique=True)

    def __unicode__(self):  #For Python 2, use __str__ on Python 3
        return self.name

class Page(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=128)
    url = models.URLField()
    views = models.IntegerField(default=0)

    def __unicode__(self):      #For Python 2, use __str__ on Python 3
        return self.title

2. 设置管理界面

打开rango/admin.py输入如下代码:

from django.contrib import admin
from rango.models import Category, Page

admin.site.register(Category)
admin.site.register(Page)

3. 数据模型迁移

  • makemigrations app_name
$ python manage.py makemigrations rango

Migrations for 'rango':
  0001_initial.py:
    - Create model Category
    - Create model Page
  • migrate
$ python manage.py migrate

Operations to perform:
  Apply all migrations: admin, rango, contenttypes, auth, sessions
Running migrations:
  Applying rango.0001_initial... OK

MTV

在Django中创建数据驱动页面必须执行以下5步。

  1. 首先,在你应用的views.py文件中导入你要添加的模型。
  2. 在视图里访问模型,导入你需要的数据。
  3. 把模型的数据传递给模板。
  4. 设置模板给用户呈现数据。
  5. 如果还没有映射URL,映射一下吧。
添加新评论