django 入门基础示例

Demo 是最好的老师。

建立项目

创建虚拟环境

python3 -m venv ll_env

激活虚拟环境

可使用 deactivate 停止使用虚拟环境。

[root@master ~]$ source ll_env/bin/activate
(ll_env) [root@master ~]$ 
(ll_env) [looking@master ~]$ deactivate
[looking@master ~]$ 

安装指定版本的 django

(ll_env) [looking@master ~]$ pip3 install django==2.1.8
Collecting django==2.1.8
...

创建 learning_log 目录

(ll_env) [root@master ~]$ mkdir learning_log
(ll_env) [root@master ~]$ cd learning_log/
(ll_env) [root@master learning_log]$ 

在 django 中创建项目

(ll_env) [root@master learning_log]# django-admin startproject learning_log .
(ll_env) [root@master learning_log]# ls
learning_log  manage.py

创建数据库

如果出现以下错误:

TypeError: argument of type 'PosixPath' is not iterable

按照如下方法修改 learning_log 项目下的 settings.py 文件:

+ import os
  ...

- 'NAME': BASE_DIR / 'db.sqlite3',
+ 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
(ll_env) [root@master learning_log]# python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK

(ll_env) [root@master learning_log]# ls
db.sqlite3  learning_log  manage.py

查看项目

(ll_env) [root@master learning_log]# python3 manage.py runserver 0.0.0.0:8000
Performing system checks...

System check identified no issues (0 silenced).
January 12, 2021 - 10:23:00
Django version 2.1.8, using settings 'learning_log.settings'
Starting development server at http://0.0.0.0:8000/
...
[12/Jan/2021 10:24:10] "GET / HTTP/1.1" 400 61735
Invalid HTTP_HOST header: '192.168.128.139:8000'. You may need to add '192.168.128.139' to ALLOWED_HOSTS.
Bad Request: /favicon.ico

如果 Windows 中用 ip:port 访问不到的话,还需要修改一下 setting.py 配置:

...

- ALLOWED_HOSTS = []
+ ALLOWED_HOSTS = ['*']

...

再次启动就可以正常查看到了 “worked successfully” 界面了。

(ll_env) [root@master learning_log]# python3 manage.py runserver 0.0.0.0:8000
Performing system checks...

System check identified no issues (0 silenced).
January 12, 2021 - 10:29:04
Django version 2.1.8, using settings 'learning_log.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
[12/Jan/2021 10:29:08] "GET / HTTP/1.1" 200 16348
[12/Jan/2021 10:29:08] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[12/Jan/2021 10:29:08] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564
Not Found: /favicon.ico
[12/Jan/2021 10:29:08] "GET /favicon.ico HTTP/1.1" 404 1984
[12/Jan/2021 10:29:08] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304
[12/Jan/2021 10:29:08] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348
...

django 入门基础示例_第1张图片

创建应用程序

(ll_env) [root@master learning_log]# python3 manage.py startapp learning_logs
(ll_env) [root@master learning_log]# ls
db.sqlite3  learning_log  learning_logs  manage.py
(ll_env) [root@master learning_log]# ls learning_logs
admin.py  apps.py  __init__.py  migrations  models.py  tests.py  views.py

定义模型

# models.py

from django.db import models

# Create your models here.

class Topic(models.Model):
    """用户学习的主题"""
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        """返回模型的字符串表示"""
        return self.text

激活模型

在 settings.py 添加 app。

  INSTALLED_APPS = [
      'django.contrib.admin',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
      'django.contrib.staticfiles',

      # my app
+     'learning_logs',
  ]
(ll_env) [root@master learning_log]# ls
db.sqlite3  learning_log  learning_logs  manage.py
(ll_env) [root@master learning_log]# python3 manage.py makemigrations learning_logs
Migrations for 'learning_logs':
  learning_logs/migrations/0001_initial.py
    - Create model Topic
(ll_env) [root@master learning_log]# python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, learning_logs, sessions
Running migrations:
  Applying learning_logs.0001_initial... OK

创建超级用户

(ll_env) [root@master learning_log]# python3 manage.py createsuperuser
Username (leave blank to use 'root'): 
Email address: 
Password: 
Password (again): 
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

向管理网站注册模型

# admin.py

from django.contrib import admin

# Register your models here.

from learning_logs.models import Topic
admin.site.register(Topic)
(ll_env) [root@master learning_log]# python3 manage.py runserver 0.0.0.0:8000
Performing system checks...

System check identified no issues (0 silenced).
January 12, 2021 - 11:18:19
Django version 2.1.8, using settings 'learning_log.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
[12/Jan/2021 11:18:29] "GET / HTTP/1.1" 200 16348
[12/Jan/2021 11:18:29] "GET /static/admin/css/fonts.css HTTP/1.1" 304 0
...

 

django 入门基础示例_第2张图片

django 入门基础示例_第3张图片

定义模型 Entry

# models.py
...
class Entry(models.Model):
	"""学到的有关某个主题的具体知识"""
	topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
	text = models.TextField()
	date_added = models.DateTimeField(auto_now_add=True)
	
	class Meta:
		verbose_name_plural = 'entries'

	def __str__(self):
		"""返回模型的字符串表示"""
		if len(self.text) > 50:	
			return self.text[:50] + "..."
		else:
			return self.text

向管理网站注册模型 Topic

# admin.py

from django.contrib import admin

# Register your models here.

from learning_logs.models import Topic, Entry
admin.site.register(Topic)
admin.site.register(Entry)

迁移模型 Entry 

(ll_env) [root@master learning_log]# python3 manage.py makemigrations learning_logs
Migrations for 'learning_logs':
  learning_logs/migrations/0002_entry.py
    - Create model Entry

(ll_env) [root@master learning_log]# python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, learning_logs, sessions
Running migrations:
  Applying learning_logs.0002_entry... OK

django 入门基础示例_第4张图片

 

django 入门基础示例_第5张图片

 

django 入门基础示例_第6张图片

The opening is the first part of the game, roughly the first ten moves or so. In the opening, it's a good idea to do three things —bring out your bishops and knights, try to control the center of the board, and castle your king.

Of course, these are just guidelines, It will be important to learn when to follow these guidelines and when to disregard these suggestions.

------------------------------------------------------------
In the opening phase of the game, it's important to bring out your bishops and knights. These pieces are powerful and maneuverable enough to play a significant role in the beginning moves of a game.

------------------------------------------------------------
One of the most important concepts in climbing is to keep you weight on your feet as much as possible. There's a myth that climbers can hang all day on their arms. In reality, good climbers have practiced specific ways of keeping their weight over their feet whenever possible.

Django Shell

(ll_env) [root@master learning_log]# python3 manage.py shell
Python 3.6.8 (default, Aug  7 2019, 17:28:10) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from learning_logs.models import Topic
>>> Topic.objects.all()
, ]>
>>> topics = Topic.objects.all()
>>> for topic in topics:
...     print(topic.id, topic)
... 
1 Chess
2 Climbing

>>> t = Topic.objects.get(id=1)
>>> t.text
'Chess'
>>> t.date_added
datetime.datetime(2021, 1, 12, 14, 37, 24, 500078, tzinfo=)
>>> t.entry_set.all()
, ]>
>>> 

创建网页

映射 URL

[root@master learning_log]# pwd
/root/learning_log/learning_log
[root@master learning_log]# vim urls.py
# urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include(('learning_logs.urls', 'learning_logs'), namespace='learning_logs')),
]
[root@master learning_logs]# pwd
/root/learning_log/learning_logs
[root@master learning_logs]# vim urls.py
# urls.py

"""定义 learning_logs 的 URL 模式"""
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

 编写视图

[root@master learning_logs]# pwd
/root/learning_log/learning_logs
[root@master learning_logs]# vim views.py 
# views.py

from django.shortcuts import render

# Create your views here.

def index(request):
    """学习笔记的主页"""
    return render(request, 'learning_logs/index.html')

编写模板

[root@master learning_logs]# pwd
/root/learning_log/learning_logs/templates/learning_logs
[root@master learning_logs]# vim index.html
# index.html

Learning Log

Learning Log helps you keep track of your learning, for any topic you're learning about.

django 入门基础示例_第7张图片

创建其他网页

模板继承

[root@master learning_logs]# pwd
/root/learning_log/learning_logs/templates/learning_logs
[root@master learning_logs]# vim base.html
# base.html

Learning Log

{% block content %}

Learning Log helps you keep track of your learning, for any topic you're learning about.

{% endblock content %}
[root@master learning_logs]# pwd
/root/learning_log/learning_logs/templates/learning_logs
[root@master learning_logs]# vim index.html
# index.html

{% extends "learning_logs/base.html" %}

{% block content %}
  

Learning Log helps you keep track of your learning, for any topic you're learning about.

{% endblock content %}

 django 入门基础示例_第8张图片

显示所有主题页面

[root@master learning_logs]# pwd
/root/learning_log/learning_logs
[root@master learning_logs]# vim urls.py 
# urls.py

"""定义 learning_logs 的 URL 模式"""
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^topics/$', views.topics, name='topics'),
]
[root@master learning_logs]# pwd
/root/learning_log/learning_logs
[root@master learning_logs]# vim views.py
# views.py

from django.shortcuts import render
from .models import Topic

# Create your views here.

def index(request):
	"""学习笔记的主页"""	
	return render(request, 'learning_logs/index.html')

def topics(request):
	"""显示所有主题"""
	topics = Topic.objects.order_by('date_added')
	context = {'topics': topics}
	return render(request, 'learning_logs/topics.html', context)
[root@master learning_logs]# pwd
/root/learning_log/learning_logs/templates/learning_logs
[root@master learning_logs]# vim topics.html
# topics.html

{% extends "learning_logs/base.html" %}

{% block content %}
  

Topics

    {% for topic in topics %}
  • { { topic }}
  • {% empty %}
  • No topics have been added yet.
  • {% endfor %}
{% endblock content %}
[root@master learning_logs]# pwd
/root/learning_log/learning_logs/templates/learning_logs
[root@master learning_logs]# vim base.html 
# base.html

Learning Log Topics

{% block content %}

Learning Log helps you keep track of your learning, for any topic you're learning about.

{% endblock content %}

 

django 入门基础示例_第9张图片

django 入门基础示例_第10张图片

显示特定主题页面

[root@master learning_logs]# pwd
/root/learning_log/learning_logs
[root@master learning_logs]# vim urls.py 
# urls.py

"""定义 learning_logs 的 URL 模式"""
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^topics/$', views.topics, name='topics'),
    url(r'^topics/(?P\d+)/$', views.topic, name='topic'),
]
[root@master learning_logs]# pwd
/root/learning_log/learning_logs
[root@master learning_logs]# vim views.py
# views.py

from django.shortcuts import render
from .models import Topic

# Create your views here.

...

def topic(request, topic_id):
	"""显示单个主题及其所有的条目"""
	topic = Topic.objects.get(id=topic_id)
	entries = topic.entry_set.order_by('-date_added')
	context = {'topic': topic, 'entries': entries}
	return render(request, 'learning_logs/topic.html', context)
这是第一个除  request 对象外还包含另一个形参的视图函数。这个函数接受正则表达式 (?P\d+) 捕获的值,并将其存储到 topic_id 我 们使用 get() 来获取指定的主题,就像前面在  Django shell  中所做的那样。 我们获取与该主题相关联的条目,并将它们按  date_added 排序: date_added 前面的减号 指定按降序排列,即先显示最近的条目。我们将主题和条目都存储在字典 context ,再将这个字典发送给模板  topic.html
 
[root@master learning_logs]# pwd
/root/learning_log/learning_logs/templates/learning_logs
[root@master learning_logs]# vim topic.html
# topic.html

{% extends "learning_logs/base.html" %}

{% block content %}
  

Topics: { { topic }}

Entries:

    {% for entry in entries %}
  • { { entry.date_added|date:'M d, Y H:i' }}

    { { entry.text|linebreaks }}

  • {% empty %}
  • There are no entries for this topic yet.
  • {% endfor %}
{% endblock content %}
[root@master learning_logs]# pwd
/root/learning_log/learning_logs/templates/learning_logs
[root@master learning_logs]# vim topics.html
# topics.html

{% extends "learning_logs/base.html" %}

{% block content %}
  

Topics

    {% for topic in topics %}
  • { {topic}}
  • {% empty %}
  • No topics have been added yet.
  • {% endfor %}
{% endblock content %}
[root@master learning_logs]# pwd
/root/learning_log/learning_logs/templates/learning_logs
[root@master learning_logs]# vim base.html 
# base.html

Learning Log Topics

{% block content %}

Learning Log helps you keep track of your learning, for any topic you're learning about.

{% endblock content %}

 django 入门基础示例_第11张图片

django 入门基础示例_第12张图片

django 入门基础示例_第13张图片

让用户能输入数据

添加新主题

(ll_env) [root@master learning_logs]# pwd
/root/learning_log/learning_logs
(ll_env) [root@master learning_logs]# vim forms.py
# forms.py

from django import forms
from .models import Topic

class TopicForm(forms.ModelForm):
    class Meta:
        model = Topic
        fields = ['text']
        labels = {'text': ''}
[root@master learning_logs]# pwd
/root/learning_log/learning_logs
[root@master learning_logs]# vim urls.py 
# urls.py

"""定义 learning_logs 的 URL 模式"""
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^topics/$', views.topics, name='topics'),
    url(r'^topics/(?P\d+)/$', views.topic, name='topic'),
    url(r'^new_topic/$', views.new_topic, name='new_topic'),
]
(ll_env) [root@master learning_logs]# pwd
/root/learning_log/learning_logs
(ll_env) [root@master learning_logs]# vim views.py 
# views.py

from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse

from .models import Topic
from .forms import TopicForm

# Create your views here.

...

def new_topic(request):
    """添加新主题"""
    if request.method != 'POST':
        # 未提交数据:创建一个新表单
        form = TopicForm()
    else:
        # POST 提交数据,对数据进行处理
        form = TopicForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('learning_logs:topics'))
    context = {'form': form}
    return render(request, 'learning_logs/new_topic.html', context)
[root@master learning_logs]# pwd
/root/learning_log/learning_logs/templates/learning_logs
[root@master learning_logs]# vim new_topic.html
# new_topic.html

{% extends "learning_logs/base.html" %}

{% block content %}
  

Add a new topic:

{% csrf_token %} { { form.as_p }}
{% endblock content %}
[root@master learning_logs]# pwd
/root/learning_log/learning_logs/templates/learning_logs
[root@master learning_logs]# vim topics.html
# topics.html

{% extends "learning_logs/base.html" %}

{% block content %}
  

Topics

    {% for topic in topics %}
  • { {topic}}
  • {% empty %}
  • No topics have been added yet.
  • {% endfor %}
Add a new topic: {% endblock content %}

django 入门基础示例_第14张图片

 django 入门基础示例_第15张图片

django 入门基础示例_第16张图片

 

  

你可能感兴趣的:(Python,django)