发布网友 发布时间:2024-10-24 00:16
共1个回答
热心网友 时间:2024-11-02 11:13
导读:今天首席CTO笔记来给各位分享关于django如何让网站上线的相关内容,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
如何创建一个Django网站本文演示如何创建一个简单的django网站,使用的django版本为1.7。
1.创建项目
运行下面命令就可以创建一个django项目,项目名称叫mysite:
$django-admin.pystartprojectmysite
创建后的项目目录如下:
mysite
├──manage.py
└──mysite
├──__init__.py
├──settings.py
├──urls.py
└──wsgi.py
1directory,5files
说明:
__init__.py:让Python把该目录当成一个开发包(即一组模块)所需的文件。这是一个空文件,一般你不需要修改它。
manage.py:一种命令行工具,允许你以多种方式与该Django项目进行交互。键入pythonmanage.pyhelp,看一下它能做什么。你应当不需要编辑这个文件;在这个目录下生成它纯是为了方便。
settings.py:该Django项目的设置或配置。
urls.py:Django项目的URL路由设置。目前,它是空的。
wsgi.py:WSGIweb应用服务器的配置文件。更多细节,查看HowtodeploywithWSGI
接下来,你可以修改settings.py文件,例如:修改LANGUAGE_CODE、设置时区TIME_ZONE
SITE_ID=1
LANGUAGE_CODE='zh_CN'
TIME_ZONE='Asia/Shanghai'
USE_TZ=True
上面开启了[Timezone]()特性,需要安装pytz:
$sudopipinstallpytz
2.运行项目
在运行项目之前,我们需要创建数据库和表结构,这里我使用的默认数据库:
$pythonmanage.pymigrate
Operationstoperform:
Applyallmigrations:admin,contenttypes,auth,sessions
Runningmigrations:
Applyingcontenttypes.0001_initial...OK
Applyingauth.0001_initial...OK
Applyingadmin.0001_initial...OK
Applyingsessions.0001_initial...OK
然后启动服务:
$pythonmanage.pyrunserver
你会看到下面的输出:
Performingsystemchecks...
Systemcheckidentifiednoissues(0silenced).
January28,2015-02:08:33
Djangoversion1.7.1,usingsettings'mysite.settings'
Startingdevelopmentserverat
QuittheserverwithCONTROL-C.
这将会在端口8000启动一个本地服务器,并且只能从你的这台电脑连接和访问。既然服务器已经运行起来了,现在用网页浏览器访问。你应该可以看到一个令人赏心悦目的淡蓝色Django欢迎页面它开始工作了。
你也可以指定启动端口:
$pythonmanage.pyrunserver8080
以及指定ip:
$pythonmanage.pyrunserver0.0.0.0:8000
3.创建app
前面创建了一个项目并且成功运行,现在来创建一个app,一个app相当于项目的一个子模块。
在项目目录下创建一个app:
$pythonmanage.pystartapppolls
如果操作成功,你会在mysite文件夹下看到已经多了一个叫polls的文件夹,目录结构如下:
polls
├──__init__.py
├──admin.py
├──migrations
│└──__init__.py
├──models.py
├──tests.py
└──views.py
1directory,6files
4.创建模型
每一个DjangoModel都继承自django.db.models.Model
在Model当中每一个属性attribute都代表一个databasefield
通过DjangoModelAPI可以执行数据库的增删改查,而不需要写一些数据库的查询语句
打开polls文件夹下的models.py文件。创建两个模型:
importdatetime
fromdjango.dbimportmodels
fromdjango.utilsimporttimezone
classQuestion(models.Model):
question_text=models.CharField(max_length=200)
pub_date=models.DateTimeField('datepublished')
defwas_published_recently(self):
returnself.pub_date=timezone.now()-datetime.timedelta(days=1)
classChoice(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你的模型做了改变,需要迁移数据库:
$pythonmanage.pymakemigrationspolls
你会看到下面的输出日志:
Migrationsfor'polls':
0001_initial.py:
-CreatemodelChoice
-CreatemodelQuestion
-Addfieldquestiontochoice
你可以从polls/migrations/0001_initial.py查看迁移语句。
运行下面语句,你可以查看迁移的sql语句:
$pythonmanage.pysqlmigratepolls0001
输出结果:
BEGIN;
CREATETABLE"polls_choice"("id"integerNOTNULLPRIMARYKEYAUTOINCREMENT,"choice_text"varchar(200)NOTNULL,"votes"integerNOTNULL);
CREATETABLE"polls_question"("id"integerNOTNULLPRIMARYKEYAUTOINCREMENT,"question_text"varchar(200)NOTNULL,"pub_date"datetimeNOTNULL);
CREATETABLE"polls_choice__new"("id"integerNOTNULLPRIMARYKEYAUTOINCREMENT,"choice_text"varchar(200)NOTNULL,"votes"integerNOTNULL,"question_id"integerNOTNULLREFERENCES"polls_question"("id"));
INSERTINTO"polls_choice__new"("choice_text","votes","id")SELECT"choice_text","votes","id"FROM"polls_choice";
DROPTABLE"polls_choice";
ALTERTABLE"polls_choice__new"RENAMETO"polls_choice";
CREATEINDEXpolls_choice_7aa0f6eeON"polls_choice"("question_id");
COMMIT;
你可以运行下面命令,来检查数据库是否有问题:
$pythonmanage.pycheck
再次运行下面的命令,来创建新添加的模型:
$pythonmanage.pymigrate
Operationstoperform:
Applyallmigrations:admin,contenttypes,polls,auth,sessions
Runningmigrations:
Applyingpolls.0001_initial...OK
总结一下,当修改一个模型时,需要做以下几个步骤:
修改models.py文件
运行pythonmanage.pymakemigrations创建迁移语句
运行pythonmanage.pymigrate,将模型的改变迁移到数据库中
你可以阅读django-admin.pydocumentation,查看更多manage.py的用法。
创建了模型之后,我们可以通过Django提供的API来做测试。运行下面命令可以进入到pythonshell的交互模式:
$pythonmanage.pyshell
下面是一些测试:
frompolls.modelsimportQuestion,Choice#Importthemodelclasseswejustwrote.
#Noquestionsareinthesystemyet.
Question.objects.all()
[]
#CreateanewQuestion.
#Supportfortimezonesisenabledinthedefaultsettingsfile,so
#Djangoexpectsadatetimewithtzinfoforpub_date.Usetimezone.now()
#insteadofdatetime.datetime.now()anditwilldotherightthing.
fromdjango.utilsimporttimezone
q=Question(question_text="What'snew?",pub_date=timezone.now())
#Savetheobjectintothedatabase.Youhavetocallsave()explicitly.
q.save()
#NowithasanID.Notethatthismightsay"1L"insteadof"1",depending
#onwhichdatabaseyou'reusing.That'snobiggie;itjustmeansyour
#databasebackendpreferstoreturnintegersasPythonlonginteger
#objects.
q.id
1
#AccessmodelfieldvaluesviaPythonattributes.
q.question_text
"What'snew?"
q.pub_date
datetime.datetime(2012,2,26,13,0,0,775217,tzinfo=UTC)
#Changevaluesbychangingtheattributes,thencallingsave().
q.question_text="What'sup?"
q.save()
#objects.all()displaysallthequestionsinthedatabase.
Question.objects.all()
[Question:Questionobject]
打印所有的Question时,输出的结果是[Question:Questionobject],我们可以修改模型类,使其输出更为易懂的描述。修改模型类:
fromdjango.dbimportmodels
classQuestion(models.Model):
#...
def__str__(self):#__unicode__onPython2
returnself.question_text
classChoice(models.Model):
#...
def__str__(self):#__unicode__onPython2
returnself.choice_text
接下来继续测试:
frompolls.modelsimportQuestion,Choice
#Makesureour__str__()additionworked.
Question.objects.all()
[Question:What'sup?]
#DjangoprovidesarichdatabaselookupAPIthat'sentirelydrivenby
#keywordarguments.
Question.objects.filter(id=1)
[Question:What'sup?]
Question.objects.filter(question_text__startswith='What')
[Question:What'sup?]
#Getthequestionthatwaspublishedthisyear.
fromdjango.utilsimporttimezone
current_year=timezone.now().year
Question.objects.get(pub_date__year=current_year)
Question:What'sup?
#RequestanIDthatdoesn'texist,thiswillraiseanexception.
Question.objects.get(id=2)
Traceback(mostrecentcalllast):
...
DoesNotExist:Questionmatchingquerydoesnotexist.
#Lookupbyaprimarykeyisthemostcommoncase,soDjangoprovidesa
#shortcutforprimary-keyexactlookups.
#ThefollowingisidenticaltoQuestion.objects.get(id=1).
Question.objects.get(pk=1)
Question:What'sup?
#Makesureourcustommethodworked.
q=Question.objects.get(pk=1)
#GivetheQuestionacoupleofChoices.Thecreatecallconstructsanew
#Choiceobject,doestheINSERTstatement,addsthechoicetotheset
#ofavailablechoicesandreturnsthenewChoiceobject.Djangocreates
#asettoholdthe"otherside"ofaForeignKeyrelation
#(e.g.aquestion'schoice)whichcanbeaccessedviatheAPI.
q=Question.objects.get(pk=1)
#Displayanychoicesfromtherelatedobjectset--nonesofar.
q.choice_set.all()
[]
#Createthreechoices.
q.choice_set.create(choice_text='Notmuch',votes=0)
Choice:Notmuch
q.choice_set.create(choice_text='Thesky',votes=0)
Choice:Thesky
c=q.choice_set.create(choice_text='Justhackingagain',votes=0)
#ChoiceobjectshaveAPIaccesstotheirrelatedQuestionobjects.
c.question
Question:What'sup?
#Andviceversa:QuestionobjectsgetaccesstoChoiceobjects.
q.choice_set.all()
[Choice:Notmuch,Choice:Thesky,Choice:Justhackingagain]
q.choice_set.count()
3
#TheAPIautomaticallyfollowsrelationshipsasfarasyouneed.
#Usedoubleunderscorestoseparaterelationships.
#Thisworksasmanylevelsdeepasyouwant;there'snolimit.
#FindallChoicesforanyquestionwhosepub_dateisinthisyear
#(reusingthe'current_year'variablewecreatedabove).
Choice.objects.filter(question__pub_date__year=current_year)
[Choice:Notmuch,Choice:Thesky,Choice:Justhackingagain]
#Let'sdeleteoneofthechoices.Usedelete()forthat.
c=q.choice_set.filter(choice_text__startswith='Justhacking')
c.delete()
上面这部分测试,涉及到djangoorm相关的知识,详细说明可以参考Django中的ORM。
5.管理admin
Django有一个优秀的特性,内置了Djangoadmin后台管理界面,方便管理者进行添加和删除网站的内容.
新建的项目系统已经为我们设置好了后台管理功能,见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后台管理界面:
$pythonmanage.pycreatesuperuser
Username(leaveblanktouse'june'):admin
Emailaddress:
Password:
Password(again):
Superusercreatedsuccessfully.
总结
最后,来看项目目录结构:
mysite
├──db.sqlite3
├──manage.py
├──mysite
│├──__init__.py
│├──settings.py
│├──urls.py
│├──wsgi.p