# 1. 快速開始的helloworld # # 在下載好的django路徑下執行django的安裝 # https://pypi.python.org/pypi/Django/1.6.4 python3 setup.py install # # 新建django項目 django-admin.py startproject mysite # # 運行django項目 python3 manage.py runserver [port] # # 建立一個app python3 manage.py startapp appname # 2. model定義 # 模型定義特殊字段定義(後面一些Field被略去) # AutoFiled SlugField SmallIntegerField #Date,DateTime,Decimal,Char,File,Float,FilePath,Text#,Time,Binary,Boolean,BigInterger,NullBoolean,Image,#Interger,OneToOne #PositiveSmallIntegerField, #PositiveIntergerField,Url,Email # # 建立一個model實體 from django.db import models class Publisher(models.Model): name = models.CharField(max_length=30) // 普通字段 website = models.URLField() // url類型字段 email = models.EmailField() // email類型字段 publication_date = models.DateField() // 時間類型字段 publisher = models.ForeignKey(Publisher) // 引用信息(外鍵) # # 建立一個關聯實體(此段來源自博客園@2BiTT) class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __unicode__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) # # 實體經常使用方法(此段來源自博客園@2BiTT) class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __unicode__(self): return u'%s %s' % (self.first_name, self.last_name) def get_absolute_url(self): return "/people/%i/" % self.id # 3. 將實體生成到數據庫 # 模型檢測 (須要在settings.py中註冊此app) python3 manage.py validate # # 模型生成sql語句查看 python3 manage.py sqlall modelname (app的名字) # # 模型生成到db 要生成用戶以前必須作這一步 python3 manage.py syncdb # 4. django的後臺管理操做 # 創建管理超級員 python manage.py createsuperuser # # 將model加入到admin管理列表中 在admin中 from django.contrib import admin from books.models import Publisher, Author, Book admin.site.register(Author,AuthorAdmin) # # 附加管理視圖,將管理視圖更明細 from django.contrib import admin class BookAdmin(admin.ModelAdmin): list_display = ('title', 'publisher', 'publication_date') #顯示列 list_filter = ('publication_date',) # 列過濾條件 date_hierarchy = 'publication_date' # 日期選擇條件 ordering = ('-publication_date',) # 列表日期降序排列 fields = ('title', 'authors', 'publisher') # 編輯時顯示須要添加的列 其餘列 null=True raw_id_fields = ('publisher',) # 編輯時 顯示爲id序號 # # 5. 控制視圖輸出內容 # 定義模板路徑 TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'template').replace('\\','/'), # /Users/King/Documents/Ops/Python/HelloDjango/HelloDjango # /Users/King/Documents/Ops/Python/HelloDjango/HelloDjango/template ) # # 進入項目命令行模型 python manage.py shell from django.contrib.auth.models import Publisher p = Publisher.objects.create(name='Apress',website='www.apress.com') Publisher.name = 'tuling' 全部的model都擁有一個objects管理器 使用filter方法能夠過濾obj Publisher.objects.filter(name='usa') 模糊查詢 Publisher.objects.filter(name__contains='usa') # 使用get方法可完成一個對象的獲取,若是返回不止一個對象就會報錯 Publisher.DoesNotExist 使用order_by 排序 可 - 倒排 p = Publisher.objects.filter(id=52).update(name='Apress Publishing') p.delete() 刪除對象 p.save() # # 導入靜態文件 在setting.py中 # 靜態資源區域 # 這是一個根目錄區域 對應實際文件目錄 STATIC_ROOT = 'static/' # 這是url配置目錄 給urls用的 STATIC_URL = 'static/' 在模板頁面中 <link rel="stylesheet" href="{{ STATIC_URL }}css/bootstrap.css"> <script type="text/javascript" src="{{ STATIC_URL }}js/bootstrap.js"></script> 在urls.py的配置中 from django.conf.urls.static import static 在最後加入 admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'HelloDjango.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), (r'^$', latest_books), ) + (static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)) 在views.py對應的輸出視圖中 return render_to_response('index.html', { 'book_list': book_list, 'STATIC_URL': STATIC_URL, }) # 6. 其餘解決方案 配置文件中 STATICFILES_DIRS = ( '/Users/King/Documents/Ops/Python/HelloDjango/static', ) # # # 一個app基本的設置 # # import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) ROOT_URLCONF = 'HelloDjango.urls' SECRET_KEY = '&%s+d(0$motnksr+0o+oo8z9k=2h*7gd%gnnylrnc^w5#nut)h' DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) WSGI_APPLICATION = 'HelloDjango.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = True # # Absolute filesystem path to the directory that will hold user-uploaded files. # # Example: "/home/media/media.lawrence.com/media/" # MEDIA_ROOT = '' # # # URL that handles the media served from MEDIA_ROOT. Make sure to use a # # trailing slash. # # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" # MEDIA_URL = '' # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # TEMPLATE_DIRS = ('templates',) # 靜態資源區域 # 這是一個根目錄區域 對應實際文件目錄 STATIC_ROOT = 'static/' # 這是url配置目錄 給urls用的 STATIC_URL = 'static/' # STATICFILES_DIRS = ( # # Put strings here, like "/home/html/static" or "C:/www/django/static". # # Always use forward slashes, even on Windows. # # Don't forget to use absolute paths, not relative paths. # ) # STATICFILES_FINDERS = ( # 'django.contrib.staticfiles.finders.FileSystemFinder', # 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # # 'django.contrib.staticfiles.finders.DefaultStorageFinder', # ) # 定義模板路徑 # List of callables that know how to import templates from various sources. # TEMPLATE_LOADERS = ( # 'django.template.loaders.filesystem.Loader', # 'django.template.loaders.app_directories.Loader', # # 'django.template.loaders.eggs.Loader', # ) TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates').replace('\\','/'), ) INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', ) # LOGGING = { # 'version': 1, # 'disable_existing_loggers': False, # 'filters': { # 'require_debug_false': { # '()': 'django.utils.log.RequireDebugFalse' # } # }, # 'handlers': { # 'mail_admins': { # 'level': 'ERROR', # 'filters': ['require_debug_false'], # 'class': 'django.utils.log.AdminEmailHandler' # } # }, # 'loggers': { # 'django.request': { # 'handlers': ['mail_admins'], # 'level': 'ERROR', # 'propagate': True, # }, # } # }
Django框架中的基本交互javascript
# 服務器端展現數據 from django.shortcuts import render_to_response def search(request): return render_to_response('search.html', {'books':books,}) # # search.html的數據渲染 , 利用模板 {% if books %} <ul> 發現 {{ books | length }} 本書 {% for book in books %} <li>{{ book.title }}</li> {% endfor %} </ul> {% else %} <p>沒有查詢到任何圖書信息</p> {% endif %}
# 客戶端提交數據 search_form.html <html><head> <title>Search</title></head> <body> {% if error %} <p style="color:red;">請輸入查詢條件</p> {% endif %} <form action="/search_form/" method="get"> <input type="text" name="q"> <input type="submit" value="Search"> </form> </body> </html> # # 收集客戶端信息 # from django.http import HttpResponse # request.path() get_host() get_full_path() get_isecure() # request.META[] 包含http頭信息 def search_form(request): if 'q' in request.GET and request.GET['q']: q = request.GET['q'] books = Book.objects.filter(title__icontains=q) return render_to_response('search_result.html', {'books':books,'query':q}) else: return render_to_response('search.html', {'error': True})
最後附博文中基本實現代碼一份css
下一篇計劃Django的高級應用
html