1. 程式人生 > >【Django Series - 02】Django 基礎知識:語法、教程

【Django Series - 02】Django 基礎知識:語法、教程

Django Series(Django2.1.2 + Anaconda3)

(一)安裝並配置 Django 環境 ||| 基於 Django 進行 Web 開發

(二)Django 基礎知識:語法、教程

(三)使用者管理模組:建立使用者、登入、退出

(四)資料的增刪改:使用者提交資料,驗證資料的有效性並傳輸至後臺(jQuery.post、jQuery.getJSON)

(五)基於 "xlsxwriter  + BytesIO"(Python3)生成 Excel 報表 ||| Python2 StringIO.StringIO()


說明:本系列教程根據最近實踐過程進行整理、總結和分享。由於時間和精力有限,發表時內容分析部分可能不是很完整

,後續有時間會慢慢補充。同時!!也希望感興趣的同學可以提出一些細節問題和建議,我會根據這些問題進一步整理和完善哈。

更新日誌:

20181019:發表第一版,為什麼選擇Django、要選擇哪個Django和Python版本、Django基礎教程。


前言:

在知乎上提的一個問題:link

大家都在使用什麼框架進行Web開發呢?Django怎麼樣呢?Django跟哪個Python版本較好呢?

這一系列問題,官網有給了一些滿意的答案(link):

  • WHY Django?- With Django, you can take Web applications from concept to launch in a matter of hours.
    Django takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.
  • What Python version should I use with Django?Python 3 is recommended. Django 1.11 is the last version to support Python 2.7. Support for Python 2.7 and Django 1.11 ends in 2020. Since newer versions of Python are often faster, have more features, and are better supported, the latest version of Python 3 is recommended. You don’t lose anything in Django by using an older release, but you don’t take advantage of the improvements and optimizations in newer Python releases.
    Third-party applications for use with Django are, of course, free to set their own version requirements.
  • Is Django stable? - Yes, it’s quite stable. Companies like Disqus, Instagram, Pinterest, and Mozilla have been using Django for many years. Sites built on Django have weathered traffic spikes of over 50 thousand hits per second.
  • Should I use the stable version or development version? - Generally, if you’re using code in production, you should be using a stable release. The Django project publishes a full stable release every nine months or so, with bugfix updates in between. These stable releases contain the API that is covered by our backwards compatibility guarantees; if you write code against stable releases, you shouldn’t have any problems upgrading when the next official version is released.
  • Which sites use Django? - DjangoSites.org features a constantly growing list of Django-powered sites.

Django 官網提供的系列基礎教程:

建議感興趣的同學可以過一遍這些基礎教程,後續的Web開發過程中,離不開這些基礎教程。

  1. https://docs.djangoproject.com/en/2.1/intro/tutorial01/

  2. https://docs.djangoproject.com/en/2.1/intro/tutorial02/

  3. https://docs.djangoproject.com/en/2.1/intro/tutorial03/

  4. https://docs.djangoproject.com/en/2.1/intro/tutorial04/

  5. https://docs.djangoproject.com/en/2.1/intro/tutorial05/

  6. https://docs.djangoproject.com/en/2.1/intro/tutorial06/

  7. https://docs.djangoproject.com/en/2.1/intro/tutorial07/


Django-2.1.2 基礎知識:

基本命令整理:

## 檢視 django 版本
python -m django --version

##
django-admin startproject mysite

##
python manage.py runserver
python manage.py runserver 8080
python manage.py runserver 0:8000

## 
python manage.py startapp polls

## dataset
python manage.py check
python manage.py migrate
# By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.
python manage.py makemigrations polls

python manage.py sqlmigrate polls 0001

## 
python manage.py shell

## 
python manage.py createsuperuser

Projects vs. apps

What’s the difference between a project and an app? 
An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. 
A project is a collection of configuration and apps for a particular website. 
A project can contain multiple apps. An app can be in multiple projects.

Apps can be used in multiple projects, and you can package and distribute them for use by others in their projects.

urls --- path

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]


## path(route, view, kwargs, name)

# required
route: a string that contains a URL pattern.
view: When Django finds a matching pattern, it calls the specified view function with an HttpRequest object as the first argument and any “captured” values from the route as keyword arguments. We’ll give an example of this in a bit.

# optional
kwargs: Arbitrary keyword arguments can be passed in a dictionary to the target view. 
name: Naming your URL lets you refer to it unambiguously from elsewhere in Django, especially from within templates.

re_path()  v.s.  path()

## path patterns
path('<int:question_id>/', views.detail, name='detail')

## The following path converters are available by default:
# str - Matches any non-empty string, excluding the path separator, '/'. This is the default if a converter isn’t included in the expression.
# int - Matches zero or any positive integer. Returns an int.
# slug - Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. For example, building-your-1st-django-site.
# uuid - Matches a formatted UUID. For example, 075194d3-6885-417e-a8a8-6c931e272f00.
# path - Matches any non-empty string, including the path separator, '/'. 


## Using regular expressions
#  To do so, use re_path() instead of path().
urlpatterns = [
    path('articles/2003/', views.special_case_2003),
    re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
    re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
    re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<slug>[\w-]+)/$', views.article_detail),
]

python manage.py migrate

The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file and the database migrations shipped with the app (we’ll cover those later).

models.py

## The code is straightforward. 
## Each model is represented by a class that subclasses django.db.models.Model. 
## Each model has a number of class variables, each of which represents a database field in the model.

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

## Finally, note a relationship is defined, using ForeignKey. 
## That tells Django each Choice is related to a single Question. 
## Django supports all the common database relationships: many-to-one, many-to-many, and one-to-one.

python managy.py shell

在介面中引入 html:

{% include "footer.html" %}