Django学习笔记之一
一、Windows下安装 Django
1、下载安装包解压后放到本地目录如C:\Django-1.7.2 官网地址:https://www.djangoproject.com/download/
2、打开命令行,输入 cd C:\Django-1.7.2 然后定位到当前目录
3、输入 python setup.py install 开始安装
4、配置各种环境变量,C:\Python34\;C:\Python34\Scripts;C:\Python34\Lib\site-packages\Django-1.7.2-py3.4.egg\django;
5、验证是否安装成功
D:\project\mysite>python
>>> import django
>>> print(django.get_version())
1.7.2 安装成功!
二、通过官网的简单投票系统学习使用[https://docs.djangoproject.com/en/1.7/intro/tutorial01/]
1、创建一个项目,先在命令行cd 到想要创建项目所在的目录如D:\project\,然后输入如下命令
django-admin.py startproject mysite
此时已经自动创建了如下目录
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
2、使用已经自动安装了的SQLite
python manage.py migrate
3、启动服务器,通过如下网址可以访问网页
python manage.py runserver
Performing system checks... 0 errors found
January 27, 2015 - 15:50:53
Django version 1.7, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
4、在网站下创建一个名叫pools的APP投票应用
python manage.py startapp polls
被创建的目录如下:
polls/
__init__.py
admin.py
migrations/
__init__.py
models.py
tests.py
views.py
5、创建Models(MVC架构中的model,用于自动生成对应的数据库)
from django.db import models class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published') class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
2)激活Models
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
2.1)在命令行执行
python manage.py makemigrations polls #这是第一步,创建对Model的修改,可以打开polls/migrations/0001_initial.py文件查看代码格式
Migrations for 'polls':
0001_initial.py:
- Create model Question
- Create model Choice
- Add field question to choice 或者输入:python manage.py sqlmigrate polls 0001查看创建了些什么,结果如下:
BEGIN;
CREATE TABLE polls_question (
"id" serial NOT NULL PRIMARY KEY,
"question_text" varchar(200) NOT NULL,
"pub_date" timestamp with time zone NOT NULL
); CREATE TABLE polls_choice (
"id" serial NOT NULL PRIMARY KEY,
"question_id" integer NOT NULL,
"choice_text" varchar(200) NOT NULL,
"votes" integer NOT NULL
); CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id"); ALTER TABLE "polls_choice"
ADD CONSTRAINT polls_choice_question_id_246c99a640fbbd72_fk_polls_question_id
FOREIGN KEY ("question_id")
REFERENCES "polls_question" ("id")
DEFERRABLE INITIALLY DEFERRED;
COMMIT;
2.2)在命令行执行
python manage.py migrate #这是第二步,应用刚才创建的对Model的修改,sqlLite数据库里面会自动根据Model来修改数据库
Apply all migrations: admin, contenttypes, polls, auth, sessions
Running migrations:
Applying <migration name>... OK 此时数据库已经创建完了,可以打开python测试一下
>>> from polls.models import Question, Choice
>>> Question.objects.all()
[]
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
>>> q.save()
>>> q.id
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
>>> q.question_text = "What's up?"
>>> q.save()
>>> Question.objects.all()
[<Question: Question object>] 修改polls/models.py
from django.db import models class Question(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.question_text class Choice(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.choice_text
添加自定义函数
import datetime from django.db import models
from django.utils import timezone class Question(models.Model):
# ...
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
再随便玩玩
>>> from polls.models import Question, Choice
# 确保 __str__() 可用.
>>> Question.objects.all()
[<Question: What's up?>]
# Django自带的数据查询 API
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
>>> Question.objects.filter(question_text__startswith='What')
[<Question: What's up?>]
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>
>>> Question.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Question matching query does not exist.
>>> Question.objects.get(pk=1)
<Question: What's up?>
# 确保我们的自定义函数可用.
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True
>>> q = Question.objects.get(pk=1)
>>> q.choice_set.all()
[]
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
>>> c.question
<Question: What's up?>
>>> q.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> q.choice_set.count()
3
>>> Choice.objects.filter(question__pub_date__year=current_year)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
Django学习笔记之一的更多相关文章
- Django 学习笔记之四 QuerySet常用方法
		
QuerySet是一个可遍历结构,它本质上是一个给定的模型的对象列表,是有序的. 1.建立模型: 2.数据文件(test.txt) 3.文件数据入库(默认的sqlite3) 入库之前执行 数据库同步命 ...
 - Django 学习笔记之三  数据库输入数据
		
假设建立了django_blog项目,建立blog的app ,在models.py里面增加了Blog类,同步数据库,并且建立了对应的表.具体的参照Django 学习笔记之二的相关命令. 那么这篇主要介 ...
 - Django学习笔记(五)—— 表单
		
疯狂的暑假学习之 Django学习笔记(五)-- 表单 參考:<The Django Book> 第7章 1. HttpRequest对象的信息 request.path ...
 - Django学习笔记(三)—— 型号 model
		
疯狂暑期学习 Django学习笔记(三)-- 型号 model 參考:<The Django Book> 第5章 1.setting.py 配置 DATABASES = { 'defaul ...
 - Django 学习笔记(二)
		
Django 第一个 Hello World 项目 经过上一篇的安装,我们已经拥有了Django 框架 1.选择项目默认存放的地址 默认地址是C:\Users\Lee,也就是进入cmd控制台的地址,创 ...
 - Django 学习笔记(五)模板标签
		
关于Django模板标签官方网址https://docs.djangoproject.com/en/1.11/ref/templates/builtins/ 1.IF标签 Hello World/vi ...
 - Django 学习笔记(四)模板变量
		
关于Django模板变量官方网址:https://docs.djangoproject.com/en/1.11/ref/templates/builtins/ 1.传入普通变量 在hello/Hell ...
 - Django 学习笔记(三)模板导入
		
本章内容是将一个html网页放进模板中,并运行服务器将其展现出来. 平台:windows平台下Liunx子系统 目前的目录: hello ├── manage.py ├── hello │ ├── _ ...
 - Django 学习笔记(七)数据库基本操作(增查改删)
		
一.前期准备工作,创建数据库以及数据表,详情点击<Django 学习笔记(六)MySQL配置> 1.创建一个项目 2.创建一个应用 3.更改settings.py 4.更改models.p ...
 - Django 学习笔记(六)MySQL配置
		
环境:Ubuntu16.4 工具:Python3.5 一.安装MySQL数据库 终端命令: sudo apt-get install mysql-server sudo apt-get install ...
 
随机推荐
- supersr--控制器的生命周期:
			
调用顺序为 1 init函数(init;initWithFrame;initWithCoder;等)--初始化 2 awakeFromNib--在loadView之前的工作放在这里 3 viewDid ...
 - 模拟赛1102d2
			
/* φ(n)=φ(p^k)=p^k-p^(k-1)=(p-1)*p^(k-1) φ(m*n)=φ(m)*φ(n) 直接套公式做,因为分解质因数时,只分解一个数,所以可以不打素数表,只将n分解到√n就 ...
 - IOS管理文件和目录NSFileManager
			
1.常见的NSFileManager文件方法 -(NSData *)contentsAtPath:path //从一个文件读取数据 -(BOOL)createFileAtPath: path cont ...
 - iOS - 定制多样式二维码
			
二维码/条形码是按照某种特定的几何图形按一定规律在平台(一维/二维方向上)分布的黑白相间的图形纪录符号信息.使用若干个与二进制对应的几何形体来表示文字数值信息. 最常见的二维码功能包括信息获取.网 ...
 - perl检查变量是否定义
			
my $label = defined($pieces[0]) ? $pieces[0] : ""; my @alreadyAddedCol = $node1->{DB}-& ...
 - 三、jQuery--Ajax基础--Ajax全接触--Ajax在JS中的应用
			
Ajax的全称:Asynchronous JavaScript And XML(异步的 JavaScript 和 XML). Ajax不是某种编程语言,是一种在无需重新加载整个网页的情况下能够更新部分 ...
 - PHP面向对象——异常处理
			
Error_reporting(0); //在网站正式上线的时候不准他报任何错误. 错误级别为不允许报错 Exception 是所有异常的基类. 测试并捕捉一个错误的例子: class mysq ...
 - 【Agorithm】一次一密加密解密算法
			
#include<iostream> #include<cstdio> #include<cstdlib> #include<ctime> #inclu ...
 - 玩转SSRS第十篇---自定义代码
			
提到SSRS 那么就不得不提一下自定义代码的功能,通过自定义代码,有时候可以解决一些比较复杂的问题,比如将让指定的数据行应用指定的属性值.此篇将演示如何通过简单结构的自定义代码进行报表样式的基本设计. ...
 - HDU1502 Regular Words
			
链接:http://acm.hdu.edu.cn/showproblem.php?pid=1502 思路:当只有两个数时,可以用卡特兰数做,当三个数时,没想到卡特兰数的做法.可以使用动态规划. 状态转 ...