项目结构
1.建立项目
File -->> New Project...
第一个Location是项目所在的目录,第二个Location是项目独立的Python运行环境,我们称之为Virtualenv。
Base interpreter是Python安装目录下的python.exe。
刚创建的Django项目如下所示:
在Terminal窗口输入命令python manage.py runserver
也可以启动项目。
在浏览器中访问http://127.0.0.1:8000/
,看到下面这个页面表明项目到目前为止一切正常。
2.创建应用程序
Django项目由一系列应用程序组成,它们协同工作,让项目成为一个整体。
实际上,PyCharm的Terminal窗口已经处于Django项目独立的运行环境,执行python manage.py startapp learning_logs
命令创建一个应用程序:
创建完应用程序后,就可以在项目中看到新增的应用程序的目录。
2.1 定义模型
# untitled/learning_logs/models.py
from django.db import models
class Topic(models.Model):
"""A topic the user is learning about."""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
"""Return a string representation of the model."""
return self.text
class Entry(models.Model):
"""Something specific learned about a topic."""
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):
"""Return a string representation of the model."""
return self.text[:50] + "..."
2.2 激活模型
# untitled/untitled/settings.py
# ···
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 我的应用程序
'learning_logs',
]
# ···
2.3 创建数据库
接着,先后执行命令python manage.py makemigrations learning_logs
和python manage.py migrate
,前者生成一个文件0001_initial.py告诉Django如何修改数据库,后者就让Django修改数据库了。
2.4 Django管理网站
为应用程序定义模型时,Django提供的管理网站让你能够轻松地处理模型。
创建超级用户:
向管理网站注册模型:
# untitled/learning_logs/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)
使用超级用户访问管理网站http://127.0.0.1:8000/admin/
。
我们可以在管理网站管理模型的数据:
2.5 Django shell
输入一些数据后,就可通过交互式终端会话以编程方式查看这些数据了。这种交互式环境称为Django shell,是测试项目和排除其故障的理想之地。
3.创建网页
使用Django创建网页的过程通常分三个阶段:定义URL、编写视图和编写模板。
每个URL都被映射到特定的视图——视图函数获取并处理网页所需的数据。视图函数通常调用一个模板,后者生成浏览器能够理解的网页。
3.1 映射URL
http://127.0.0.1:8000/
默认返回Django网站,我们修改这一点,将这个URL映射到“学习笔记”的主页。
# untitled/untitled/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),
url(r'', include('learning_logs.urls', namespace='learning_logs'))
]
"""定义learning_logs的URL模式"""
# untitled/learning_logs/urls.py
from django.conf.urls import url
from . import views
app_name = 'learning_logs'
urlpatterns = [
# 主页
url(r'^$', views.index, name='index'),
]
3.2 编写视图
# untitled/learning_logs/views.py
from django.shortcuts import render
# Create your views here.
def index(request):
"""学习笔记的主页"""
return render(request, 'learning_logs/index.html')
3.3 编写模板
<!-- untitled/templates/learning_logs/index.html -->
<p>Learning Log</p>
<p>Learning Log helps you keep track of your learning, for my topic you're learning about.</p>
3.3.1 父模板
<!-- untitled/templates/learning_logs/base.html -->
<p>
<a href="{% url 'learning_logs:index' %}">Learning Log</a>
</p>
{% block content %}{% endblock %}
3.3.2 子模板
<!-- untitled/templates/learning_logs/index.html -->
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Learning Log helps you keep track of your learning, for any topic you're
learning about.</p>
{% endblock content %}
显示所有主题的页面
"""定义learning_logs的URL模式"""
# untitled/learning_logs/urls.py
from django.conf.urls import url
from . import views
app_name = 'learning_logs'
urlpatterns = [
# 主页
url(r'^$', views.index, name='index'),
url(r'^topics/$', views.topics, name='topics'),
]
# untitled/learning_logs/views.py
#···
def topics(request):
topics = Topic.objects.order_by('date_added')
context = {'topics' : topics}
return render(request, 'learning_logs/topics.html', context)
# ···
<!-- untitled/templates/learning_logs/topics.html -->
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Topics</p>
<ul>
{% for topic in topics %}
<li>{{ topic }}</li>
{% empty %}
<li>No topics have been added yet.</li>
{% endfor %}
</ul>
{% endblock content %}
显示特定主题的页面
"""定义learning_logs的URL模式"""
# untitled/learning_logs/urls.py
from django.conf.urls import url
from . import views
app_name = 'learning_logs'
urlpatterns = [
# 主页
url(r'^$', views.index, name='index'),
url(r'^topics/$', views.topics, name='topics'),
url(r'^topics/(?P<topic_id>d+)/$', views.topic, name='topic'),
]
# untitled/learning_logs/views.py
#···
def topic(request, topic_id):
"""Show a single topic, and all its entries."""
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)
#···
<!-- untitled/templates/learning_logs/topic.html -->
{% extends 'learning_logs/base.html' %}
{% block content %}
<p>Topic: {{ topic }}</p>
<p>Entries:</p>
<ul>
{% for entry in entries %}
<li>
<p>{{ entry.date_added|date:'M d, Y H:i' }}</p>
<p>{{ entry.text|linebreaks }}</p>
</li>
{% empty %}
<li>
There are no entries for this topic yet.
</li>
{% endfor %}
</ul>
{% endblock content %}
参考资料:《Python编程从入门到实践》—【美】Eric Matthes 著