如何搭建django?

2023-03-07 16:56:11 8 0
卡卡

导读:本篇文章恰卡编程网来给大家介绍有关如何搭建django的相关内容,希望对大家有所帮助,一起来看看吧。

ubuntu怎么部署django

(一):背景在线

如何搭建django?

由于现在工作的需要,我需要使用python来进行一个网站后台的开发,python之前接触过其语法的学习,基本的东西已经掌握,但是当时自学的时候是学得python3.5,而现在要使用python2.7进行实现,所以,先不管了,大多是一样的,有部分是不一样的,慢慢搞吧.

(二):编程环境搭建

我的网站开发是在ubuntu系统下进行的,我们都知道,ubuntu系统在安装的时候,是自带python2.7的,所以,pyhthon就不用进行安装了.我们还需要安装的有:

django ‘1.6.0’

mysql 5.6

ngix

好了,下面我们就搭建我们的环境.

安装Django

首先我们需要安装的是django,我们直接使用命令进行安装:

sudo apt-get install python-django -y1

安装完成之后,我们来测试一下我们的django的版本.使用下面的命令:

python

import django

django.get_version()

1234

python怎么搭建django框架

运行环境

Windows 7(64位) + Python 2.7 + Django 1.7.1

1.安装django框架

当然你首先要有python环境,对于学python的朋友们这个就不多说了~~

我使用的是setuptools工具来安装的,setuptools是python中安装第三方模块常用的安装工具

1.1安装setuptools工具(如果会安装的可以直接跳过)

先从这个地址下载ez_setup.py:

(在页面最下面)

我下载的是setuptools-7.0.zip,将其解压,将解压的setuptools-7.0文件放到一个目录,我这里假定将其放到C:\workspace目录下

打开命令行cmd,在cmd中切换到C:\workspace\setuptools-7.0,即setuptools-7.0安装目录

运行命令:

python ez_setup.py

该命令会安装setuptools工具,安装后打开你的python安装目录下的Scripts目录(我的是C:\Python27\Scripts),会看到easy_install.exe等文件

注意将python安装目录下的Scripts目录(我的是C:\Python27\Scripts)添加到环境变量path,否则下面的easy_install命令会报错

1.2安装django框架

在cmd中输入:

easy_install django

有的安装过程可能会提示缺少vc++包,根据提示网址(我忘了~)下载包,我下载的是VCForPython27.msi,安装vc++后再执行安装

这样就自动安装了django,是不是很方便,哈哈

2.创建django项目,这里假定在c:\workspace\djangoTest下创建(和java有点差别,java是直接创建项目就可以了,python是要先创建项目再在项目里创建app)

进入c:\workspace\djangoTest目录,输入:

django-admin startproject mytodo #网上很多是python django-admin.py startproject mytodo,版本不一样可能命令有细微差别

就创建了mytodo项目

3.启动调试服务器

进入c:\workspace\djangoTest\djangoTest\mytodo目录:

cd mytodo

然后输入:

python manage.py runserver

在浏览器中输入,看能否访问页面

4.创建app

输入命令:python manage.py startapp todo

就在mytodo项目下创建了一个app,即todo

编辑mytodo/settings.py文件,在INSTALLED_APPS添加条目todo

INSTALLED_APPS = (

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.sites',

'todo',

)

即在最后添加一行todo(有的版本是项目名+app名,即mytodo.todo)

再次输入:python manage.py runserver看看你app是否配置好了,养成边写边测试的好习惯,哈哈~

5.配置数据库

django默认的是使用SQLite数据库作为后台数据库,仍然打开mytodo/settings.py,可以看到下面一段:

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.sqlite3',

'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

}

}

这就是django项目的数据库配置,默认是使用SQLite,我们就使用使用默认配置,安装SQLite数据库,不需要修改配置文件

听到又要安装数据库,大家肯定又觉得好复杂,其实在python里安装三方模块,数据库什么的很简单,一条命令就可以搞定了~~

输入命令:

easy_install pysqlite

这样就安装了SQLite数据库

安装完数据库,我们也测试一下,输入命令:

python manage.py syncdb

出现successfully提示就安装成功了,打开mytodo目录,看看里面是否有一个db.sqlite3文件,这就是上面配置的数据库文件

怎么在vps上搭建django服务器

安装pip

下载

[plain] view plain copy

#wget --no-check-certificate

解压并进入解压后的文件夹

[plain] view plain copy

#tar zvxf 1.5.5.tar.gz

#cd pip-1.5.5/

安装

[plain] view plain copy

#python setup.py install

四、使用pip安装django

[plain] view plain copy

#pip install django

pycharm 怎么建django

打开PyCharm官网,选择Download,进入下载页面。

这时会出现2个版本,左边的那个是购买版,可以试用30天;右边那个是社区版,免费的,我们一般选择右边社区版。

下载完后进行安装,一直选择下一步就可以了,我就不详细介绍了。安装完后运行PyCharm,新建项目。此时建的项目并不是Django项目,这个还需要我们自己设置。

安装Django,使用命令安装,我这里是用的cmder,非常好用的控制台命令窗口,替代了cmd。进入到Python27的目录下,使用命令 pip install Django== 1.8.3 ,执行完就OK了。

新建Django项目,我这里是使用命令创建项目的。

django-admin startproject HelloDjango 创建HelloDjango项目

然后进入到HelloDjango项目根目录下,运行命令创建hello模块

python manage.py startapp hello

此时PyCharm中就有一个HelloDjango项目了。

现在我们来搭建一个简单的web服务。

修改views.py文件

修改urls.py文件

两个文件修改完后,就可以启动项目了,执行命令

python manage.py migrate

python manage.py runserver

此时项目已经启动起来了,它会告诉我们访问地址,按照地址进行访问就OK了。

如何创建一个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

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=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]

打印所有的 Question 时,输出的结果是 [Question: Question object],我们可以修改模型类,使其输出更为易懂的描述。修改模型类:

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()

[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)

# 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()

上面这部分测试,涉及到 django orm 相关的知识,详细说明可以参考 Django中的ORM。

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 的自动化测试、持久化、中间件、国 际 化等知识。

如何windows 7下搭建django开发环境

方法/步骤

1、安装python

由于之前《01Windows 7系统下安装Python》已经详细介绍过python的安装这里不再赘述;

2、安装ipython

ipython 是一个 python 的交互式 shell,比默认的python shell 好用得多,支持变量自动补全,自动缩进,支持 bash shell 命令,内置了许多很有用的功能和函数。在windows 7下只要pip install ipython 就装好了,通过 ipython 启动。

3、安装django

1、通过pip安装在windows 7下只要pip install django就装好了。

2、也可以通过源码安装,git clone 下载源码;通过python setup.py install安装;

4、创建第一个django应用

安装django后会有django-admin命令,通过django-admin startproject mysite即可创建;

进入目录通过python manage.py runserver.启动应用。

结语:以上就是恰卡编程网为大家整理的关于如何搭建django的相关内容解答汇总了,希望对您有所帮助!如果解决了您的问题欢迎分享给更多关注此问题的朋友喔~

收藏
分享
海报
0 条评论
8
上一篇:python中unicode编码有多少位(2023年最新分享) 下一篇:djangogirls是什么?

本站已关闭游客评论,请登录或者注册后再评论吧~

忘记密码?

图形验证码