最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【记录】基于通过pip安装官网Django后,折腾第一个Django的app

Django crifan 3907浏览 0评论

之前已通过pip去安装好了Django,现在接着参考: Getting Started with Django – Introduction and Tutorial (之前页面已失效:Writing your first Django app, part 1
去折腾第一个django的app:


1.创建名为firstApp的项目:

E:\Dev_Root\WebServer\Django\fisrtApp>django-admin.py startproject firstApp

E:\Dev_Root\WebServer\Django\fisrtApp>

2. 然后,验证是否正常工作:

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>dir
 驱动器 E 中的卷是 Develop
 卷的序列号是 0003-B490

 E:\Dev_Root\WebServer\Django\fisrtApp\firstApp 的目录

2012/10/14  18:39    <DIR>          .
2012/10/14  18:39    <DIR>          ..
2012/10/14  18:39    <DIR>          firstApp
2012/10/14  18:39               261 manage.py
               1 个文件            261 字节
               3 个目录  2,133,356,544 可用字节

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py runserver
Validating models...

0 errors found
Django version 1.4.1, using settings 'firstApp.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

可见,是可以正常工作的。
3.去访问: http://127.0.0.1:8000/ 可以看到Django已经正常运行了: django worked  
4.然后去把
E:\Dev_Root\WebServer\Django\fisrtApp\firstApp\firstApp\settings.py
中的配置改为自己的:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'E:/Dev_Root/WebServer/Django/fisrtApp/firstApp/firstApp/db/sqlite3_firstApp.db',    # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
#TIME_ZONE = 'America/Chicago'
TIME_ZONE = 'Asia/Shanghai'

5. 接着再去运行manage.py syncdb:

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'administrator'): admin
E-mail address: [email protected]
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

相应的,也看到了
E:\Dev_Root\WebServer\Django\fisrtApp\firstApp\firstApp\db
下面有了db文件:sqlite3_firstApp.db
6. 然后去启动poll的app:

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py startapp polls

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>

然后再给models.py添加内容,变为:

from django.db import models

# Create your models here.
class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()

再添加到settings.py中:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'polls',
)

再接着运行:

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py sql polls
BEGIN;
CREATE TABLE "polls_poll" (
    "id" integer NOT NULL PRIMARY KEY,
    "question" varchar(200) NOT NULL,
    "pub_date" datetime NOT NULL
)
;
CREATE TABLE "polls_choice" (
    "id" integer NOT NULL PRIMARY KEY,
    "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"),
    "choice" varchar(200) NOT NULL,
    "votes" integer NOT NULL
)
;
COMMIT;

然后又试了一堆命令:

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py validate
0 errors found

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py sqlcustom polls

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py sqlclear polls

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py sqlindexes polls
BEGIN;
CREATE INDEX "polls_choice_763e883" ON "polls_choice" ("poll_id");
COMMIT;

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py sqlall polls
BEGIN;
CREATE TABLE "polls_poll" (
    "id" integer NOT NULL PRIMARY KEY,
    "question" varchar(200) NOT NULL,
    "pub_date" datetime NOT NULL
)
;
CREATE TABLE "polls_choice" (
    "id" integer NOT NULL PRIMARY KEY,
    "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"),
    "choice" varchar(200) NOT NULL,
    "votes" integer NOT NULL
)
;
CREATE INDEX "polls_choice_763e883" ON "polls_choice" ("poll_id");
COMMIT;

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>

接着同步数据库:

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py syncdb
Creating tables ...
Creating table polls_poll
Creating table polls_choice
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

然后测试了添加一个poll:

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py shell
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from polls.models import Poll,Choice
>>> Poll.objects.all()
[]
>>> from django.utils import timezone
>>> p = Poll(question="What's new?", pub_date=timezone.now())
>>> p.save()
>>> p.id
1
>>> p.question
"What's new?"
>>> p.pub_date
datetime.datetime(2012, 10, 14, 12, 46, 24, 445000, tzinfo=<UTC>)
>>> p.question = "What's up?"
>>> p.save()
>>> Poll.objects.all()
[<Poll: Poll object>]
>>>

然后继续试了试,都是正常的:

E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py shell
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from polls.models import Poll,Choice
>>> Poll.objects.all()
[<Poll: What's up?>]
>>> Poll.objects.filter(id=1)
[<Poll: What's up?>]
>>> Poll.objects.filter(question__startswith='What')
[<Poll: What's up?>]
>>> Poll.objects.get(pub_date__year=2012)
<Poll: What's up?>
>>> Poll.objects.get(id=2)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "E:\dev_install_root\Python27\lib\site-packages\django\db\models\manager.py", line 131, in get
    return self.get_query_set().get(*args, **kwargs)
  File "E:\dev_install_root\Python27\lib\site-packages\django\db\models\query.py", line 366, in get
    % self.model._meta.object_name)
DoesNotExist: Poll matching query does not exist.
>>> Poll.objects.get(pk=1)
<Poll: What's up?>
>>> p = Poll.objects.get(pk=1)
>>> p.was_published_recently()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "E:\Dev_Root\WebServer\Django\fisrtApp\firstApp\polls\models.py", line 11, in was_published_recently
    return self.pub_date >= (timezone.now() - datetime.timedelta(days=1));
NameError: global name 'timezone' is not defined
>>> p.was_published_recently()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "E:\Dev_Root\WebServer\Django\fisrtApp\firstApp\polls\models.py", line 11, in was_published_recently
    def was_published_recently(self):
NameError: global name 'timezone' is not defined
>>> ^Z


E:\Dev_Root\WebServer\Django\fisrtApp\firstApp>manage.py shell
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from polls.models import Poll,Choice
>>> p = Poll.objects.get(pk=1)
>>> p.was_published_recently()
True
>>> p = Poll.objects.get(pk=1)
>>> p.choce_set.all()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Poll' object has no attribute 'choce_set'
>>> p.choice_set.all()
[]
>>> p.choice_set.create(choice='Not much', votes=0)
<Choice: Not much>
>>> p.choice_set.create(choice='The sky', votes=0)
<Choice: The sky>
>>> c = p.choice_set.create(choice='Just hacking again', votes=0)
>>> c.poll
<Poll: What's up?>
>>> p.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> p.choice_set.count()
3
>>> Choice.objects.filter(poll__pub_date__year=2012)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> c = p.choice_set.filter(choice__startswith='Just hacking')
>>> c.delete()
>>>

至此,第一个app,就结束了。

转载请注明:在路上 » 【记录】基于通过pip安装官网Django后,折腾第一个Django的app

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.161 seconds, using 22.17MB memory