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