【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" %}

猜你喜欢

转载自blog.csdn.net/Houchaoqun_XMU/article/details/83180483