Django 學習筆記,django學習筆記
1.Django Intor2.Django Install(1) PIP安裝
sudo apt-get isntall python-pipsudo pip install Django
(2) 源碼安裝
/usr/local/share/Django/Django-1.8.3.tar.gzDjango-1.8.3├── AUTHORS├── build├── dist├── django├── Django.egg-info├── docs├── extras├── INSTALL├── LICENSE├── MANIFEST.in├── PKG-INFO├── README.rst├── scripts├── setup.cfg├── setup.py└── tests
sudo python setup.py install
3.Django Project(1) 建立項目
root@kallen:Django#django-admin startproject MyProjroot@kallen:Django# tree MyProj/MyProj/├── manage.py└── MyProj ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py
__init__.py:Django項目是Python包,這個檔案是用來告訴Python這個檔案夾當做一個包。在Python術語中,包是一組模組的集合,主要用來把相似的檔案分組,防止出現命名衝突。
manage.py:這個腳步用來管理你的項目,你可以把它看做是你項目的的django-admin.py版本,其實,manage.py和django-admin.py是共用相同的後台代碼。
settings.py: 這是Django項目的主要設定檔,在這個檔案裡面,你可以具體說明很多選項,包括資料庫設定、網頁語言、需要turn
on的Django功能。
urls.py:這是另外一個設定檔。你可以把它看做是介於URLS和用來處理它們的Python方法之間的匹配;
(http://www.cnblogs.com/bluescorpio/archive/2009/11/28/1612805.html)
(2) 建立應用
root@kallen:Django#python manage.py startapp jobs└── MyProj ├── jobs │ ├── admin.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── manage.py └── MyProj
(3) 建立實體類
from django.db import modelsclass Job(models.Model): pub_date = models.DateField() job_title = models.CharField(max_length=50) job_description = models.TextField() location = models.ForeignKey(Location) def __str__(self): return "%s (%s)" % (self.job_title, self.location)
(4) 查看資料庫模式
root@kallen:/home/kallen/Python/Django/MyProj# python manage.py sql jobsBEGIN;CREATE TABLE `jobs_location` ( `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `city` varchar(50)NOT NULL, `state` varchar(50), `country` varchar(50)NOT NULL);CREATE TABLE `jobs_job` ( `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `pub_date` date NOT NULL, `job_title` varchar(50)NOT NULL, `job_description` longtext NOT NULL, `location_id` integerNOT NULL);ALTER TABLE `jobs_job` ADD CONSTRAINT `location_id_refs_id_35f2feb6` FOREIGN KEY (`location_id`) REFERENCES `jobs_location` (`id`);COMMIT;
【常見錯誤】
$ python manage.py sql jobsCommandError: App 'jobs' has migrations. Only the sqlmigrate and sqlflush commandscan be used when an app has migrations.
【解決辦法】 刪除jobs下的migrations就可以了;
(5) 檢查資料庫模式
root@kallen:/home/kallen/Python/Django/MyProj#python manage.py validate/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/core/management/commands/validate.py:15: RemovedInDjango19Warning:"validate" has been deprecated in favor of"check".RemovedInDjango19Warning)System check identified no issues (0 silenced).root@kallen:/home/kallen/Python/Django/MyProj#python manage.py makemigrationsMigrations for 'jobs':0001_initial.py:- Create model Job- Create model Location- Add field location to jobroot@kallen:/home/kallen/Python/Django/MyProj#python manage.py migrateOperations to perform: Synchronize unmigrated apps: staticfiles, messages Apply all migrations: admin, contenttypes, jobs, auth, sessionsSynchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL...Running migrations: Rendering model states... DONE Applying jobs.0001_initial... OK
(6) 啟動測試伺服器
root@kallen:/home/kallen/Python/Django/MyProj#python manage.py runserverPerforming system checks...System check identified no issues (0 silenced).You have unapplied migrations; your app may not work properly until they are applied.Run 'python manage.py migrate' to apply them.August 14,2015-05:55:23Django version 1.8.3, using settings 'MyProj.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.
(7) 後台管理
root@kallen:/home/kallen/Python/Django/MyProj#python manage.py syncdb
(8) 註冊模型
from django.contrib issmport admin# Register your models here.# Register my models of job for mapping # utility class Location & Job.# Kallen Ding, Agu 17 2015from .models import Location, Job admin.site.register(Location)admin.site.register(Job)
4.Django FAQ(1) 匯入MySQL錯誤
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module
【解決辦法】安裝mysql-python模組
安裝步驟:
sudo apt-get install python-setuptoolssudo apt-get install libmysqld-devsudo apt-get install libmysqlclient-dev sudo apt-get install python-devsudo easy_install mysql-python
測試下: 在python互動式視窗,import MySQLdb 試試,不報錯的話,就證明安裝好了。
(2) 匯入model對象出錯
>>> from jobs.models import Jobdjango.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
【解決辦法】
>>>from django.conf import settings >>> settings.configure()
(3) CSRF Verification Failed
Forbidden (403)CSRF verification failed. Request aborted.HelpReason given for failure: CSRF token missing or incorrect.In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:Your browser is accepting cookies.The view function passes a request to the template's render method.In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.You're seeing the help section of this page because you have DEBUG =Truein your Django settings file. Change that to False, and only the initial error message will be displayed.You can customize this page using the CSRF_FAILURE_VIEW setting.
【解決辦法】
第一種:在表單裡加上{% csrf_token %}
就行了;
第二種:在Settings裡的MIDDLEWARE_CLASSES增加配置:
'django.middleware.csrf.CsrfViewMiddleware','django.middleware.csrf.CsrfResponseMiddleware',
方法二不可行:
ImportError: Module "django.middleware.csrf" does not define a "CsrfResponseMiddleware" attribute/class
在測試環境下只需要將這兩行注釋即可;
【參考文章】
http://queengina.com/2014/10/15/Django%E7%B3%BB%E5%88%97%EF%BC%88%E4%BA%8C%EF%BC%89/
http://stackoverflow.com/questions/6315960/djangos-querydict-bizarre-behavior-bunches-post-dictionary-into-a-single-key
著作權聲明:本文為博主原創文章,未經博主允許不得轉載|Copyright ©2011-2015, Kallen Ding, All Rights Reserved.