Django1.7学习笔记(一)

来源:互联网 发布:python 股票数据分析 编辑:程序博客网 时间:2024/06/05 03:38

              最近在学习Django,英文不好,就找了一些中文资料,最全的就是The Django Book 2.0中文版链接:http://docs.30c.org/djangobook2/index.html,试着看了一下还不错,但是书上讲的是Django1.1的版本,号称是兼容Django1.9,我用的最新版为Django1.7,还是有一些差别的,所以,结合这本书和Django1.7的官方文档,加上自己的一些实验和理解,将Django1.7的大概开发过程记录下来,希望对大家有帮助,本人学生党,菜鸟,欢迎大牛们指导!

开发环境:Ubuntu Kylin14.10,Python 2.7.8,Django1.7,mysql5.5,IDE Pycharm3.13


1.安装python和Django

python Ubuntu自带,默认的是2.X版本,Django可通过#easy_install django或者到官网下载安装,这个不多讲


2.创建项目

安装完django后因该会自动安装django-admin命令,没有的话会提示你是否安装的,然后选择一个文件夹建立项目,这里就为mysite,执行命令

$django-admin startproject mysite

此时会自动建立mysite文件夹,文件夹目录结构如下:

mysite/                         #只是Django项目的容器,可以随便起名

        manage.py #命令行工具,用来和Django交互,重要!!!

        mysite/                  #Python的项目管理包,所以需要__init__.py,

             __init__.py       #初始化文件,不用管

             settings.py       #Django的配置文件

             urls.py              #Django的URL配置文件

             wsgi.py             #WSGI兼容的Web服务器的一个入口点,以满足您的项目

如果不想这么麻烦的话可以直接用IDE,我用的是Pycharm,还不错,直接建一个Django项目,下面要说的什么App也会自动建好,如下图:



三.数据库设置

现在主要是编辑setting.py和用manage.py工具了,打开setting.py文件,进行编辑,首先找到DATABASES字典,Django默认的数据库时SQLite,如果用SQLite的话就不用配置了,如果要用其他的数据库的话就需要配置,这里用的时mysql5.5的数据库.这是我的配置:

DATABASES = {
    'default': {
    #    'ENGINE': 'django.db.backends.sqlite3',
    #    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
          'ENGINE': 'django.db.backends.mysql',            #数据库类型
          'NAME' : 'django',     #数据库名称
          'USER' : 'root',     #用户名
          'PASSWORD' : 'root',     #数据库密码
          'HOST' : '127.0.0.1',     #主机地址,这里是本机
          'PORT' : '3306',     #数据库端口号
    }
}

这里在setting中可以修改一下时区和语言,修改为中国的时区和中文如下:

LANGUAGE_CODE ='zh-cn' 
TIME_ZONE = 'Asia/Shanghai'


另外,需要注意的INSTALLED_APPS在该文件的顶部设置。持有的是在该Django的情况下激活的所有Django应用程序的名称。应用程序可以在多个项目中使用,你可以通过包装和其他人在他们的项目分发使用,

默认情况下,INSTALLED_APPS包含以下应用程序,所有这些都与Django默认生成的:

  • django.contrib.admin -管理员站点.
  • django.contrib.auth -一种认证系统。
  • django.contrib.contenttypes -内容类型的框架。
  • django.contrib.sessions -一个session框架。
  • django.contrib.messages -消息传递框架。
  • django.contrib.staticfiles -管理静态文件的框架。

这些应用都需要在数据库中建立一个表格,所以要通过一下命令建立表格:

# python manage.py migrate

运行成功结果如下:

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

#

此时数据库中已经自动建立了相应的表了.

顺便说一句,如果mysql数据库不能插入中文的问题,可以看一下我的另一篇博客:Ubuntu下mysql不能显示中文解决方法:http://blog.csdn.net/dj1174232716/article/details/40746289

四.开发服务器

现在启动django服务器:

$ python manage.py runserver

然后可以通过http://127.0.0.1:8000/访问,默认的端口是8000,且不允许其他地址访问,只能通过本地访问.但是可以通过:

$ python manage.py runserver 8080修改端口号,还可以可以通过:

$ python manage.py runserver 0.0.0.0:8000  可以让其他主机访问.


五.创建模型

您在Django写的每个应用程序包含一个Python包,遵循一定的约定。Django提供了一个实用程序,自动生成一个应用程序的基本目录结构,这样你就可以专注于编写代码,而不是创建目录。一个项目可以包含多个应用程序。一个应用程序可以在多个项目中

现在我们将创建一个应用程序(APP),通过:

$python manage.py startapp polls  我们创建了一个名为polls的应用程序,目录结构变成下面的结构:

mysite/ #只是Django项目的容器,可以随便起名

        manage.py #命令行工具,用来和Django交互,重要!!!

        mysite/                   #Python的项目管理包,所以需要__init__.py,

              __init__.py       #初始化文件,不用管

              settings.py       #Django的配置文件

              urls.py              #Django的URL配置文件

              wsgi.py            #WSGI兼容的Web服务器的一个入口点,以满足您的项目

         polls/

migrations/

                         __init_.py

               __init__.py

               admin.py

               models.py

               tests.py

               views.py

然后试着建立一个数据库模型:

polls/models.py
from django.db import modelsclass 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)
类名为数据库中表名,属性为字段,还设置了字段的类型和约束.


六.激活模型

Django的模型是需要激活或者说安装后才能使用的需要在settings.py中安装,编辑如下:

mysite/settings.py
INSTALLED_APPS = (    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    'polls',)
添加最后一项polls一项即可.然后运行以下命令:

$ python manage.py makemigrations polls

会看到如下内容:

Migrations for 'polls':
  0001_initial.py:
    - Create model Choice
    - Create model Question
    - Add field question to choice

通过运行makemigrations,你告诉Django的,你已经做了一些改动,以你的模型(在这种情况下,你已经取得了新的),并且你希望更改存储为一个迁移.然后通过:

$ python manage.py sqlmigrate polls 0001

让Django自己创建SQL语句,然后通过命令:

$python manage.py migrate

将这些SQL执行,在数据库中创建相应的表,会看到如下提示:

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


七.通过Django的API访问数据库中的数据

可以通过Django提供的API来访问数据库中的数据而不用利用SQL语句来读取数据.

可以进入Django提供的shell来操作一下数据:

$python  manage.py  shell  进入shell

如果你不想使用manage.py,没问题。只需设置DJANGO_SETTINGS_MODULE环境变量mysite.settings,启动一个普通的Python外壳,并成立了Django的:

>>> import django>>> django.setup()
现在通过代码看看Django是怎样通过API来操作数据的:

>>> from polls.models import Question, Choice   # Import the model classes we just wrote.# No questions are in the system yet.>>> Question.objects.all()[]# Create a new Question.# Support for time zones is enabled in the default settings file, so# Django expects a datetime with tzinfo for pub_date. Use timezone.now()# instead of datetime.datetime.now() and it will do the right thing.>>> from django.utils import timezone>>> q = Question(question_text="What's new?", pub_date=timezone.now())# Save the object into the database. You have to call save() explicitly.>>> q.save()# Now it has an ID. Note that this might say "1L" instead of "1", depending# on which database you're using. That's no biggie; it just means your# database backend prefers to return integers as Python long integer# objects.>>> q.id1# Access model field values via Python attributes.>>> q.question_text"What's new?">>> q.pub_datedatetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)# Change values by changing the attributes, then calling save().>>> q.question_text = "What's up?">>> q.save()# objects.all() displays all the questions in the database.>>> Question.objects.all()[<Question: Question object>]

>>> from polls.models import Question, Choice# Make sure our __str__() addition worked.>>> Question.objects.all()[<Question: What's up?>]# Django provides a rich database lookup API that's entirely driven by# keyword arguments.>>> Question.objects.filter(id=1)[<Question: What's up?>]>>> Question.objects.filter(question_text__startswith='What')[<Question: What's up?>]# Get the question that was published this year.>>> from django.utils import timezone>>> current_year = timezone.now().year>>> Question.objects.get(pub_date__year=current_year)<Question: What's up?># Request an ID that doesn't exist, this will raise an exception.>>> Question.objects.get(id=2)Traceback (most recent call last):    ...DoesNotExist: Question matching query does not exist.# Lookup by a primary key is the most common case, so Django provides a# shortcut for primary-key exact lookups.# The following is identical to Question.objects.get(id=1).>>> Question.objects.get(pk=1)<Question: What's up?># Make sure our custom method worked.>>> q = Question.objects.get(pk=1)>>> q.was_published_recently()True# Give the Question a couple of Choices. The create call constructs a new# Choice object, does the INSERT statement, adds the choice to the set# of available choices and returns the new Choice object. Django creates# a set to hold the "other side" of a ForeignKey relation# (e.g. a question's choice) which can be accessed via the API.>>> q = Question.objects.get(pk=1)# Display any choices from the related object set -- none so far.>>> q.choice_set.all()[]# Create three choices.>>> 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)# Choice objects have API access to their related Question objects.>>> c.question<Question: What's up?># And vice versa: Question objects get access to Choice objects.>>> q.choice_set.all()[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>>> q.choice_set.count()3# The API automatically follows relationships as far as you need.# Use double underscores to separate relationships.# This works as many levels deep as you want; there's no limit.# Find all Choices for any question whose pub_date is in this year# (reusing the 'current_year' variable we created above).>>> Choice.objects.filter(question__pub_date__year=current_year)[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]# Let's delete one of the choices. Use delete() for that.>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')>>> c.delete()
以上实例均来子Django1.7的官方文档.

好了一个简单的Django开发环境基本上搭建好了,下次我们来看看更多细节,怎样开发一个应用程序.

未完待续!



0 0
原创粉丝点击