pythoninteger
❶ Django的网页背景如何更改(2023年最新整理)
导读:很多朋友问到关于Django的网页背景如何更改的相关问题,本文首席CTO笔记就来为大家做个详细解答,供大家参考,希望对大家有所帮助!一起来看看吧!
djangohtml网页内有{%csrf_token%}{{uf.as_p}}这样模板,怎么替换!DOCTYPEhtml
html
body
inputtype="text"id="a"value="0"+inputtype="text"id="b"value="0"inputtype="button"onclick=result()value="="inputtype="text"id="c"value="0"
scripttype="text/javascript"
functionresult()
{
a=document.getElementById('a').value;
a=parseFloat(a);
b=document.getElementById('b').value;
b=parseFloat(b);
c=document.getElementById('c');
c.value=(a+b)+"";
}
/script
/body
/html
如何创建一个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","choice_text"varchar(200)NOTNULL,"votes"integerNOTNULL);
CREATETABLE"polls_question"("id","question_text"varchar(200)NOTNULL,"pub_date"datetimeNOTNULL);
CREATETABLE"polls_choice__new"("id","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#.
#Noquestionsareinthesystemyet.
Question.objects.all()
[]
#CreateanewQuestion.
#,so
#_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
#
#objects.
q.id
1
#.
q.question_text
"What'snew?"
q.pub_date
datetime.datetime(2012,2,26,13,0,0,775217,tzinfo=UTC)
#,thencallingsave().
q.question_text="What'sup?"
q.save()
#objects.all().
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?]
#'sentirelydrivenby
#keywordarguments.
Question.objects.filter(id=1)
[Question:What'sup?]
Question.objects.filter(question_text__startswith='What')
[Question:What'sup?]
#.
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:.
#,soDjangoprovidesa
#shortcutforprimary-keyexactlookups.
#.objects.get(id=1).
Question.objects.get(pk=1)
Question:What'sup?
#Makesureourcustommethodworked.
q=Question.objects.get(pk=1)
#.Thecreatecallconstructsanew
#Choiceobject,doestheINSERTstatement,addsthechoicetotheset
#.Djangocreates
#asettoholdthe"otherside"ofaForeignKeyrelation
#(e.g.aquestion'schoice)whichcanbeaccessedviatheAPI.
q=Question.objects.get(pk=1)
#--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)
#.
c.question
Question:What'sup?
#Andviceversa:.
q.choice_set.all()
[Choice:Notmuch,Choice:Thesky,Choice:Justhackingagain]
q.choice_set.count()
3
#.
#.
#;there'snolimit.
#_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.c
❷ 如何在django上新建项目(导入django项目)
导读:本篇文章首席CTO笔记来给大家介绍有关如何在django上新建项目的相关内容,希望对大家有所帮助,一起来看看吧。
django新建项目win下python环境配置
1)使用pycharm--file--NewProject--Django
点击create创建,等待程序安装完毕
linux安装mysql
win安装mysql
1)配置setting
本人习惯将app放入apps里
进入apps目录下
程序目录
requirements.txt
修改django_demo/_init_.py
django创建项目将django-admin所在的文件夹bin放到path里
确保.py文件是用pythonconsole打开
Django创建项目
在Run、Runconfiguration中,进入PyDevDjango,选择你的项目,在右边“MainMole”里,用${workspace_loc:项目名/manage.py}即:工作目录下的,项目名称目录下的,manage.py。也可以直接指向物理路径。在Arguments参数选项里,可以加上:runserver0.0.0.0:8000,让它用8000端口来测试。
如何在django上自动创建createuperuser1.创建项目
运行面命令创建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
前面创建项目并且功运行现创建appapp相于项目模块
项目目录创建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","choice_text"varchar(200)NOTNULL,"votes"integerNOTNULL);
CREATETABLE"polls_question"("id","question_text"varchar(200)NOTNULL,"pub_date"datetimeNOTNULL);
CREATETABLE"polls_choice__new"("id","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#.
#Noquestionsareinthesystemyet.
Question.objects.all()
[]
#CreateanewQuestion.
#,so
#_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
#
#objects.
q.id
1
#.
q.question_text
"What'snew?"
q.pub_date
datetime.datetime(2012,2,26,13,0,0,775217,tzinfo=)
#,thencallingsave().
q.question_text="What'sup?"
q.save()
#objects.all().
Question.objects.all()
[]
打印所Question输结[]我修改模型类使其输更易懂描述修改模型类:
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()
[]
#'sentirelydrivenby
#keywordarguments.
Question.objects.filter(id=1)
[]
Question.objects.filter(question_text__startswith='What')
[]
#.
fromdjango.utilsimporttimezone
current_year=timezone.now().year
Question.objects.get(pub_date__year=current_year)
#RequestanIDthatdoesn'texist,thiswillraiseanexception.
Question.objects.get(id=2)
Traceback(mostrecentcalllast):
...
DoesNotExist:.
#,soDjangoprovidesa
#shortcutforprimary-keyexactlookups.
#.objects.get(id=1).
Question.objects.get(pk=1)
#Makesureourcustommethodworked.
q=Question.objects.get(pk=1)
#.Thecreatecallconstructsanew
#Choiceobject,doestheINSERTstatement,addsthechoicetotheset
#.Djangocreates
#asettoholdthe"otherside"ofaForeignKeyrelation
#(e.g.aquestion'schoice)whichcanbeaccessedviatheAPI.
q=Question.objects.get(pk=1)
#--nonesofar.
q.choice_set.all()
[]
#Createthreechoices.
q.choice_set.create(choice_text='Notmuch',votes=0)
q.choice_set.create(choice_text='Thesky',votes=0)
c=q.choice_set.create(choice_text='Justhackingagain',votes=0)
#.
c.question
#Andviceversa:.
q.choice_set.all()
[,,]
q.choice_set.count()
3
#.
#.
#;there'snolimit.
#_dateisinthisyear
#(reusingthe'current_year'variablewecreatedabove).
Choice.objects.filter(question__pub_date__year=current_year)
[,,]
#Let'sdeleteoneofthechoices.Usedelete()forthat.
c=q.choice_set.filter(choice_text__startswith='Justhacking')
c.delete()
面部测试涉及djangoorm相关知识详细说明参考DjangoORM
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.py
├──polls
│├──__init__.py
│├──admin.py
│├──migrations
││├──0001_initial.py
││├──__init__.py
│├──models.py
│├──tem
❸ django中如何通过迁移查看数据库(2023年最新分享)
导读:很多朋友问到关于django中如何通过迁移查看数据库的相关问题,本文首席CTO笔记就来为大家做个详细解答,供大家参考,希望对大家有所帮助!一起来看看吧!
django中的migrate怎么迁移数据到数据库中databasemigrations是laravel最强大的功能之一。数据库迁移可以理解为数据库的版本控制器。
在database/migrations目录中包含两个迁移文件,一个建立用户表,一个用于用户密码重置。
在迁移文件中,up方法用于创建数据表,down方法用于回滚,也就是删除数据表。
django迁移过后没有数据库django迁移过后没有数据库可以:
修改数据库中相应表的字符集。修改整个数据库的字符集。修改mysql配置文件/etc/my.cnf.d/server.cnf,重启数据库。
如何解决Django1.8在migrate时失败
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","choice_text"varchar(200)NOTNULL,"votes"integerNOTNULL);
CREATETABLE"polls_question"("id","question_text"varchar(200)NOTNULL,"pub_date"datetimeNOTNULL);
CREATETABLE"polls_choice__new"("id","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#.
#Noquestionsareinthesystemyet.
Question.objects.all()
[]
#CreateanewQuestion.
#,so
#_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
#
#objects.
q.id
1
#.
q.question_text
"What'snew?"
q.pub_date
datetime.datetime(2012,2,26,13,0,0,775217,tzinfo=UTC)
#,thencallingsave().
q.question_text="What'sup?"
q.save()
#objects.all().
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?]
#'sentirelydrivenby
#keywordarguments.
Question.objects.filter(id=1)
[Question:What'sup?]
Question.objects.filter(question_text__startswith='What')
[Question:What'sup?]
#.
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:.
#,soDjangoprovidesa
#shortcutforprimary-keyexactlookups.
#.objects.get(id=1).
Question.objects.get(pk=1)
Question:What'sup?
#Makesureourcustommethodworked.
q=Question.objects.get(pk=1)
#.Thecreatecallconstructsanew
#Choiceobject,doestheINSERTstatement,addsthechoicetotheset
#.Djangocreates
#asettoholdthe"otherside"ofaForeignKeyrelation
#(e.g.aquestion'schoice)whichcanbeaccessedviatheAPI.
q=Question.objects.get(pk=1)
#--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)
#.
c.question
Question:What'sup?
#Andviceversa:.
q.choice_set.all()
[Choice:Notmuch,Choice:Thesky,Choice:Justhackingagain]
q.choice_set.count()
3
#.
#.
#;there'snolimit.
#_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<
❹ Django项目怎么创建管理员(2023年最新整理)
导读:很多朋友问到关于Django项目怎么创建管理员的相关问题,本文首席CTO笔记就来为大家做个详细解答,供大家参考,希望对大家有所帮助!一起来看看吧!
Django创建超级管理员摘要:进入项目路径:pythonmanage.pycreatesuperuser按照提示输入相应的用户名,邮箱和密码即可
进入项目路径:
pythonmanage.pycreatesuperuser?
按照提示输入相应的用户名,邮箱和密码即可
以上是Django创建超级管理员的内容。
django怎么在admin里显示数据库的内容操作方法:首先要运行pythonmanage.pycreatesuperuser命令来创建一个管理员账户。
然后在url中输入/admin即可到达管理员登录页,登录之后会发现并没有数据库中要显示的项目,因为我们还没有注册。
接下来我们注册要在admin中管理的数据模型;在admin.py中注册模型。然后刷新页面,即可看到ContactMessage这个数据表了,可以在里边增删进行简单的增删改查。
Django1.74版本取消syncdb后,请问怎么创建admin账号
首先没有取消syncdb
.只是在1.6的基础增加了south的功能1.7数据库初始化的方法是先执行pythonmanage.pymakemigrations然后再执行pythonmanage.pymigrate#会询问你是否创建admin,依次输入账号和密码即可
如何正确使用DjangoAdmin1.DjangoAdmin不适合最终用户使用
Djangoadmin是为管理员设计的,而不是给最终用户使用的.Djangoadmin的存在是为了方便管理员添加修改删除数据和管理站点任务.
2.列表显示
如上图,因为model的默认文本显示是xxxobject,所以在admin列表页中默认显示的也是xxxobject.如果希望显示更有用的信息我们可以进行如下设置:
为model写__unicode__()方法
如果希望model在列表页中显示更多项,则需要使用list_display
__unicode()__例子:
#models.py
fromdjango.dbimportmodels
classArticle(models.Model):
title=models.CharField(max_length=100)
slug=models.CharField(max_length=100)
content=models.TextField()
is_published=models.BooleanField(default=False)
def__unicode__(self):
returnself.title
#admin.py
fromdjango.contribimportadmin
from.modelsimportArticle
admin.site.register(Article)
结果:
如果希望显示其他项:
#admin.py
fromdjango.contribimportadmin
from.modelsimportArticle
classArticleAdmin(admin.ModelAdmin):
list_display=('title','is_published')
admin.site.register(Article,ArticleAdmin)
结果:
3.为ModelAdmin增加动作
我们可以为ModelAdmin增加method或function,以此使admin界面更符合我们的需求.
例如,我们希望在在admin界面中显示一个明确地URL,但当我们在model中定义了get_absolute_url()方法后,djangoadmin默认给我们的却是一个与我们想要的URL完全不同的URL.于是我们可以通过以下方法定义该URL:
#admin.py
fromdjango.contribimportadmin
fromdjango.core.urlresolversimportreverse
fromdjango.utils.htmlimportformat_html
from.modelsimportArticle
classArticleAdmin(admin.ModelAdmin):
list_display=('title','is_published',)
readonly_fields=('show_url',)
defshow_url(self,instance):
url=reverse('article_detail',kwargs={'pl':instance.pk})
response=format_html("""ahref="{0}"文章预览preview/a""",url)
returnresponse
show_url.short_description=u"文章预览"
#显示HTMLtag
#对于用户提交的数据,永远不要这么设置!
show_url.allow_tags=True
注意,allow_tags属性,其默认值是False,如果错误使用将会带来安全隐患.如果设置为True,
在admin中会允许显示HTMLtag.因此我们使用的原则是,对于用户输入的信息,永远不设置allow_tags=True.
只有当其内容是系统生成,用户无法修改的时,才能使用allow_tags=True.
4.不在多用户编辑环境使用list_editable
djangoadmin为我们提供了在列表页修改model属性的功能,这样方便管理员一次修改多个属性.如果管理员只有一个人的话,
那就没问题,但在多用户环境中时,却是会存在一个很严重的潜在问题.因为在list页提交的修改信息,记录的是位置,而不是model的主键.
举个例子,文章列表页默认按照创建顺序逆序排列,用户A打开文章列表页,并开始修改,同时用户B增加了一篇新文章,此时,
当用户A提交修改后其后的文章信息都会出错.
如何创建一个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","choice_text"varchar(200)NOTNULL,"votes"integerNOTNULL);
CREATETABLE"polls_question"("id","question_text"varchar(200)NOTNULL,"pub_date"datetimeNOTNULL);
CREATETABLE"polls_choice__new"("id","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#.
#Noquestionsareinthesystemyet.
Question.objects.all()
[]
#CreateanewQuestion.
#,so
#_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
#
#objects.
q.id
1
#.
q.question_text
"What'snew?"
q.pub_date
datetime.datetime(2012,2,26,13,0,0,775217,tzinfo=UTC)
#,thencallingsave().
q.question_text="What'sup?"
q.save()
#objects.all().
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?]
#'sentirelydrivenby
#keywordarguments.
Question.objects.filter(id=1)
[Question:What'sup?]
Question.objects.filter(question_text__startswith='What')
[Question:What'sup?]
#.
fromdjango.utilsimporttimezone
current_year=timezone.now().year
Question.objects.get(pub_date__year=current_year)
Question:What'sup?
#RequestanIDthatdoesn'texist,thiswillraiseanexception.
Que