首页 > 代码库 > Writing your first Django app--2017年5月9日

Writing your first Django app--2017年5月9日

Writing your first Django app, part 1

requriments : Django 1.8 and Python 2.7

创建项目django-admin startproject mysite
.
├── manage.py 命令行呢功能
└── mysite 项目的python包
├── __init__.py 告诉python这个目录是个python包
├── settings.py 配置文件
├── urls.py 支持的url
└── wsgi.py 兼容WSGI的web服务的进入点
更改数据库在settings文件中更改DATABASES
建表python manage.py migrate
创建app python manage.py startapp polls

python manage.py sqlmigrate polls 000
sqlmigrate命令实际上并不在数据库上运行迁移,它只是打印到屏幕上,是用于检查Django要做什么。

如果更改了model,即需要更新表
python manage.py makemigrations : create migrations for those changes
python manage.py migrate :apply those changes to the database.

python manage.py shell
manage.py 设置了 DJANGO_SETTINGS_MODULE 环境变量,which gives Django the Python import path to your mysite/settings.py file.

# mysite/polls/models.py
from django.db import models
import datetime
from django.utils import timezone

# Create your models here.

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField(date published)

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

Writing your first Django app, part 2

Writing your first Django app--2017年5月9日