导读:本篇文章首席CTO笔记来给大家介绍有关如何在django上新建项目的相关内容,希望对大家有所帮助,一起来看看吧。
django新建项目
win下python 环境配置
1)使用pycharm--file--New Project--Django
点击create创建,等待程序安装完毕
linux安装mysql
win安装mysql
1)配置setting
本人习惯将app放入apps里
进入apps目录下
程序目录
requirements.txt
修改django_demo/_ init _.py
django创建项目
将django-admin所在的文件夹bin放到path里
确保.py文件是用python console打开
Django创建项目
在 Run、Run configuration中,进入 PyDev Django,选择你的项目,在右边“Main Module”里,用 ${workspace_loc:项目名/manage.py} 即:工作目录下的,项目名称目录下的,manage.py。 也可以直接指向物理路径。 在 Arguments 参数选项里,可以加上:runserver 0.0.0.0:8000 ,让它用8000端口来测试。
如何在django上自动创建createuperuser
1. 创建项目
运行面命令创建 django 项目项目名称叫 mysite :
$ django-admin.py startproject mysite
创建项目目录:
mysite
├── manage.py
└── mysite
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
1 directory, 5 files
说明:
__init__.py :让 Python 该目录发包 (即组模块)所需文件 空文件般需要修改
manage.py :种命令行工具允许种式与该 Django 项目进行交互 键入python manage.py help看能做 应需要编辑文件;目录纯便
settings.py :该 Django 项目设置或配置
urls.py:Django项目URL路由设置目前空
wsgi.py:WSGI web 应用服务器配置文件更细节查看 How to deploy with WSGI
接修改 settings.py 文件例:修改 LANGUAGE_CODE、设置区 TIME_ZONE
SITE_ID = 1
LANGUAGE_CODE = 'zh_CN'
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = True
面启 [Time zone]() 特性需要安装 pytz:
$ sudo pip install pytz
2. 运行项目
运行项目前我需要创建数据库表结构我使用默认数据库:
$ 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
启服务:
$ python manage.py runserver
看面输:
Performing system checks...
System check identified no issues (0 silenced).
January 28, 2015 - 02:08:33
Django version 1.7.1, using settings 'mysite.settings'
Starting development server at
Quit the server with CONTROL-C.
端口8000启本服务器, 并且能台电脑连接访问 既服务器已经运行起现用网页浏览器访问 应该看令赏悦目淡蓝色 Django 欢迎页面始工作
指定启端口:
$ python manage.py runserver 8080
及指定 ip:
$ python manage.py runserver 0.0.0.0:8000
3. 创建 app
前面创建项目并且功运行现创建 app app 相于项目模块
项目目录创建 app:
$ python manage.py startapp polls
操作功 mysite 文件夹看已经叫 polls 文件夹目录结构:
polls
├── __init__.py
├── admin.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
1 directory, 6 files
4. 创建模型
每 Django Model 都继承自 django.db.models.Model
Model 每属性 attribute 都代表 database field
通 Django Model API 执行数据库增删改查, 需要写些数据库查询语句
打 polls 文件夹 models.py 文件创建两模型:
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
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)
mysite/settings.py 修改 INSTALLED_APPS 添加 polls:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
添加新 app 我需要运行面命令告诉 Django 模型做改变需要迁移数据库:
$ python manage.py makemigrations polls
看面输志:
Migrations for 'polls':
0001_initial.py:
- Create model Choice
- Create model Question
- Add field question to choice
polls/migrations/0001_initial.py 查看迁移语句
运行面语句查看迁移 sql 语句:
$ python manage.py sqlmigrate polls 0001
输结:
BEGIN;
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
CREATE TABLE "polls_choice__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));
INSERT INTO "polls_choice__new" ("choice_text", "votes", "id") SELECT "choice_text", "votes", "id" FROM "polls_choice";
DROP TABLE "polls_choice";
ALTER TABLE "polls_choice__new" RENAME TO "polls_choice";
CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");
COMMIT;
运行面命令检查数据库否问题:
$ python manage.py check
再运行面命令创建新添加模型:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, contenttypes, polls, auth, sessions
Running migrations:
Applying polls.0001_initial... OK
总结修改模型需要做几步骤:
修改 models.py 文件
运行 python manage.py makemigrations 创建迁移语句
运行 python manage.py migrate模型改变迁移数据库
阅读 django-admin.py documentation查看更 manage.py 用
创建模型我通 Django 提供 API 做测试运行面命令进入 python shell 交互模式:
$ python manage.py shell
面些测试:
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.id
1
# Access model field values via Python attributes.
q.question_text
"What's new?"
q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=)
# 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 输结 []我修改模型类使其输更易懂描述修改模型类:
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
接继续测试:
from polls.models import Question, Choice
# Make sure our __str__() addition worked.
Question.objects.all()
[]
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
Question.objects.filter(id=1)
[]
Question.objects.filter(question_text__startswith='What')
[]
# 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)
# 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)
# Make sure our custom method worked.
q = Question.objects.get(pk=1)
# 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)
q.choice_set.create(choice_text='The sky', votes=0)
c = q.choice_set.create(choice_text='Just hacking again', votes=0)
# Choice objects have API access to their related Question objects.
c.question
# And vice versa: Question objects get access to Choice objects.
q.choice_set.all()
[, , ]
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)
[, , ]
# Let's delete one of the choices. Use delete() for that.
c = q.choice_set.filter(choice_text__startswith='Just hacking')
c.delete()
面部测试涉及 django orm 相关知识详细说明参考 DjangoORM
5. 管理 admin
Django优秀特性, 内置Django admin台管理界面, 便管理者进行添加删除网站内容.
新建项目系统已经我设置台管理功能见 mysite/settings.py:
INSTALLED_APPS = (
'django.contrib.admin', #默认添加台管理功能
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mysite',
)
同已经添加进入台管理 url, mysite/urls.py 查看:
url(r'^admin/', include(admin.site.urls)), #使用设置url进入网站台
接我需要创建管理用户登录 admin 台管理界面:
$ python manage.py createsuperuser
Username (leave blank to use 'june'): admin
Email address:
Password:
Password (again):
Superuser created successfully.
总结
看项目目录结构:
mysite
├── db.sqlite3
├── manage.py
├── mysite
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
├── polls
│ ├── __init__.py
│ ├── admin.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── __init__.py
│ ├── models.py
│ ├── templates
│ │ └── polls
│ │ ├── detail.html
│ │ ├── index.html
│ │ └── results.html
│ ├── tests.py
│ ├── urls.py
│ ├── views.py
└── templates
└── admin
└── base_site.htm
通面介绍 django 安装、运行及何创建视 图模型清晰认识接深入习 django 自化测试、持久化、间件、 际 化等知识
django创建项目怎样理解
创建项目:
django-admin startproject mysite
2
新建APP(名称自定):
cd website
python manage.py startapp learn
3
把我们新定义的APP添加到setting.py中的INSTALL_APPS中:
修改vim mysite/settings.py
INSTALLED_APPS = (
'django.contrib.admin', #Django默认。
'django.contrib.auth', #默认身份验证系统。
'django.contrib.contenttypes', #默认内容类型框架。
'django.contrib.sessions', #默认session框架。
'django.contrib.messages', #默认消息框架
'django.contrib.staticfiles', #默认静态文件管理框架。
'learn',
)
备注:这一步是干什么呢? 新建的 app 如果不加到 INSTALL_APPS 中的话, django 就不能自动找到app中的模板文件(app-name/templates/下的文件)和静态文件(app-name/static/中的文件) 。
4
定义视图函数:
vim learn/views.py
注:我们定义了一个index()函数,第一个参数必须是request, 与网页发来的请求有关,可以包含get或post的内容,函数返回一行字到网页。
5
定义视图函数相关的URL(网址):
vim mysite/urls.py
6
运行并验证:
python manage.py runserver 0.0.0.0:8000
注意:如果不加0.0.0.0:8000,默认是127.0.0.1:8000,且只能本机访问。
访问验证:
7
至此,你已经启动了Django开发服务器,一个纯粹的由 Python 编写的轻量级 Web 服务器。Django 内包含了这个服务器,这样你就可以迅速开发了,在产品投入使用之前不必去配置一台生产环境下的服务器 – 例如 Apache 。
注意:**不要** 在任何类似生产环境中使用此服务器。它仅适用于开发环境。(Django提供的是 Web 框架的业务,而不是 Web 服务器。)
8
Tip:项目 ( Projects ) vs. 应用 ( apps )
项目与应用之间有什么不同之处?应用是一个提供功能的 Web 应用 – 例如:一个博客系统、一个公共记录的数据库或者一个简单的投票系统。 项目是针对一个特定的 Web 网站相关的配置和其应用的组合。一个项目可以包含多个应用。一个应用可以在多个项目中使用。
如何创建一个Django网站
本文演示如何创建一个简单的 django 网站,使用的 django 版本为1.7。
1. 创建项目
运行下面命令就可以创建一个 django 项目,项目名称叫 mysite :
$ django-admin.py startproject mysite
创建后的项目目录如下:
mysite
├── manage.py
└── mysite
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
1 directory, 5 files
说明:
__init__.py :让 Python 把该目录当成一个开发包 (即一组模块)所需的文件。 这是一个空文件,一般你不需要修改它。
manage.py :一种命令行工具,允许你以多种方式与该 Django 项目进行交互。 键入python manage.py help,看一下它能做什么。 你应当不需要编辑这个文件;在这个目录下生成它纯是为了方便。
settings.py :该 Django 项目的设置或配置。
urls.py:Django项目的URL路由设置。目前,它是空的。
wsgi.py:WSGI web 应用服务器的配置文件。更多细节,查看 How to deploy with WSGI
接下来,你可以修改 settings.py 文件,例如:修改 LANGUAGE_CODE、设置时区 TIME_ZONE
结语:以上就是首席CTO笔记为大家介绍的关于如何在django上新建项目的全部内容了,希望对大家有所帮助,如果你还想了解更多这方面的信息,记得收藏关注本站。