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 ~]$
(ll_env) [looking@master ~]$ pip3 install django==2.1.8
Collecting django==2.1.8
...
(ll_env) [root@master ~]$ mkdir learning_log
(ll_env) [root@master ~]$ cd learning_log/
(ll_env) [root@master learning_log]$
(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
...
(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
...
# 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
# 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)
(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
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.
(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()
, ]>
>>>
[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.
[root@master learning_logs]# pwd
/root/learning_log/learning_logs/templates/learning_logs
[root@master learning_logs]# vim base.html
# base.html
{% 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 %}
[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
{% 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
[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)
[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
{% block content %}
Learning Log helps you keep track of your learning, for any topic you're
learning about.
{% endblock content %}
(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:
{% 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 %}