发布网友 发布时间:2024-09-25 16:35
共1个回答
热心网友 时间:2024-09-27 22:31
导读:本篇文章首席CTO笔记来给大家介绍有关django怎么批量创建用户的相关内容,希望对大家有所帮助,一起来看看吧。
Django1.74版本取消syncdb后,请问怎么创建admin账号首先没有取消syncdb
.只是在1.6的基础增加了south的功能1.7数据库初始化的方法是先执行pythonmanage.pymakemigrations然后再执行pythonmanage.pymigrate#会询问你是否创建admin,依次输入账号和密码即可
django1.9.5怎么建立超级用户?
首先我们要新建一个用户名,用来登陆管理网站,可以使用如下命令:
pythonmanage.pycreatesuperuser
输入想要使用的用户名:
Username(leaveblanktouse'administrator'):user01
输入email:
Emailaddress:(在这里输入你的自己的邮箱帐号)
输入密码,需要输入两次,并且输入密码时不会显示出来:
Password:
Password(again):
当两次密码都相同的时候,就会提示超级帐号创建成功。
Superusercreatedsuccessfully.
运行服务:
pythonmanage.pyrunserver
django怎么建立sqlite3的用户名和密码??models.py中创建class。。一个class(swinfo)就是一个表!
pythonmanage.pyvalidatevalidate命令检查你的模型的语法和逻辑是否正确
pythonmanage.pysqlallbooks生成SQl文。
pythonmanage.pysyncdb生成数据表。
pythonmanage.pyshell
importspinfo.modelsimportswinfo
p1=swinfo(,,)
p1.save()
sw_list=swinfo.objects.all()
sw_list
[swinfo:swinfoobject,swinfo:swinfoobject]
objects是models的一个管理器,以后会经常用到!
这里我们看到swinfo的实例的名字还是swinfo,不是很容易理解。
解决方法是为Publisher对象添加一个方法__unicode__()
def__unicode__(self):
returnself.name
为了让我们的修改生效,先退出PythonShell,然后再次运行pythonmanage.pyshell进入。
sw_list
[swinfo:dog,swinfo:Cat]
插入数据
p=swinfo(,,)
p.save()
更新数据
p.name='ApressPublishing'
p.save()
*但这种更新不是轻量级的更新。
出处
如何在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"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=)
#Changevaluesbychangingtheattributes,thencallingsave().
q.question_text="What'sup?"
q.save()
#objects.all()displaysallthequestionsinthedatabase.
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()
[]
#DjangoprovidesarichdatabaselookupAPIthat'sentirelydrivenby
#keywordarguments.
Question.objects.filter(id=1)
[]
Question.objects.filter(question_text__startswith='What')
[]
#Getthequestionthatwaspublishedthisyear.
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:Questionmatchingquerydoesnotexist.
#Lookupbyaprimarykeyisthemostcommoncase,soDjangoprovidesa
#shortcutforprimary-keyexactlookups.
#ThefollowingisidenticaltoQuestion.objects.get(id=1).
Question.objects.get(pk=1)
#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)
q.choice_set.create(choice_text='Thesky',votes=0)
c=q.choice_set.create(choice_text='Justhackingagain',votes=0)
#ChoiceobjectshaveAPIaccesstotheirrelatedQuestionobjects.
c.question
#Andviceversa:QuestionobjectsgetaccesstoChoiceobjects.
q.choice_set.all()
[,,]
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)
[,,]
#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.co
热心网友 时间:2024-09-27 22:31
导读:本篇文章首席CTO笔记来给大家介绍有关django怎么批量创建用户的相关内容,希望对大家有所帮助,一起来看看吧。
Django1.74版本取消syncdb后,请问怎么创建admin账号首先没有取消syncdb
.只是在1.6的基础增加了south的功能1.7数据库初始化的方法是先执行pythonmanage.pymakemigrations然后再执行pythonmanage.pymigrate#会询问你是否创建admin,依次输入账号和密码即可
django1.9.5怎么建立超级用户?
首先我们要新建一个用户名,用来登陆管理网站,可以使用如下命令:
pythonmanage.pycreatesuperuser
输入想要使用的用户名:
Username(leaveblanktouse'administrator'):user01
输入email:
Emailaddress:(在这里输入你的自己的邮箱帐号)
输入密码,需要输入两次,并且输入密码时不会显示出来:
Password:
Password(again):
当两次密码都相同的时候,就会提示超级帐号创建成功。
Superusercreatedsuccessfully.
运行服务:
pythonmanage.pyrunserver
django怎么建立sqlite3的用户名和密码??models.py中创建class。。一个class(swinfo)就是一个表!
pythonmanage.pyvalidatevalidate命令检查你的模型的语法和逻辑是否正确
pythonmanage.pysqlallbooks生成SQl文。
pythonmanage.pysyncdb生成数据表。
pythonmanage.pyshell
importspinfo.modelsimportswinfo
p1=swinfo(,,)
p1.save()
sw_list=swinfo.objects.all()
sw_list
[swinfo:swinfoobject,swinfo:swinfoobject]
objects是models的一个管理器,以后会经常用到!
这里我们看到swinfo的实例的名字还是swinfo,不是很容易理解。
解决方法是为Publisher对象添加一个方法__unicode__()
def__unicode__(self):
returnself.name
为了让我们的修改生效,先退出PythonShell,然后再次运行pythonmanage.pyshell进入。
sw_list
[swinfo:dog,swinfo:Cat]
插入数据
p=swinfo(,,)
p.save()
更新数据
p.name='ApressPublishing'
p.save()
*但这种更新不是轻量级的更新。
出处
如何在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"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=)
#Changevaluesbychangingtheattributes,thencallingsave().
q.question_text="What'sup?"
q.save()
#objects.all()displaysallthequestionsinthedatabase.
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()
[]
#DjangoprovidesarichdatabaselookupAPIthat'sentirelydrivenby
#keywordarguments.
Question.objects.filter(id=1)
[]
Question.objects.filter(question_text__startswith='What')
[]
#Getthequestionthatwaspublishedthisyear.
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:Questionmatchingquerydoesnotexist.
#Lookupbyaprimarykeyisthemostcommoncase,soDjangoprovidesa
#shortcutforprimary-keyexactlookups.
#ThefollowingisidenticaltoQuestion.objects.get(id=1).
Question.objects.get(pk=1)
#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)
q.choice_set.create(choice_text='Thesky',votes=0)
c=q.choice_set.create(choice_text='Justhackingagain',votes=0)
#ChoiceobjectshaveAPIaccesstotheirrelatedQuestionobjects.
c.question
#Andviceversa:QuestionobjectsgetaccesstoChoiceobjects.
q.choice_set.all()
[,,]
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)
[,,]
#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.co