新闻类网站开发特点,抖音短视频制作教程,网站制作哪里可以做,网站建设报价链接#xff1a; Python and Django tutorial in Visual Studio Code
MVC的理解
在实际的程序中采用MVC的方式进行任务拆分。 Model#xff08;模型#xff09;负责封装应用程序的数据和业务逻辑部分。Model包含数据结构#xff0c;数据处理逻辑以及相关的操作方法#…链接 Python and Django tutorial in Visual Studio Code
MVC的理解
在实际的程序中采用MVC的方式进行任务拆分。 Model模型负责封装应用程序的数据和业务逻辑部分。Model包含数据结构数据处理逻辑以及相关的操作方法用于对数据进行增删改查等操作。Model模型View 用户界面和Controller用户交互逻辑相分离的方式有下面的好处
1相同业务逻辑可以被不同的View视图复用。
2Controller控制器通过用户的输入更新模型Model的状态模型Model的变化可以自动反应在关联的视图View上。
3业务规则和数据访问Model部分独立于具体的展示形式View和用户交互流程controll, 让代码更加可维护可复用。便于编程的标准化和工程化。
Django的解决方案
在很多实际的程序中需要使用存储与数据库的数据。Django通过使用Models来简化对数据库中数据的使用。Django中的Model是python的类来源于“django.db.models.Model”。原则上代表特定的数据库对象通常为 表单。相关的类在 app目录下的 models.py文件里进行定义。
Django通过在程序中定义的models来管理数据库。Django通过“migratons”功能来自动完成与数据库的交互。基本过程如下:
更改models.py文件中的models。运行Terminal命令“python manage.py makemigrations”。在migrations文件夹下面创建用于更新数据库状态的脚本。运行terminal命令 “python manage.py migrate”执行脚本更新数据库。
Django可以负责数据库的管理作为编程人员我们只需要关注在models.py中定义的models就可以了。
数据库包括db.sqlite3提供直接修改的功能但是这会造成数据的不一致。强烈建议 修改models运行 makemigrations, 运行 migrate。
数据库选型
Django默认使用db.sqlite3文件作为数据库该数据库适用于开发阶段。根据Sqlit.org官网When to use SQLite SQLite使用于日访问量在10万以下的应用。另外 SQLite不适用于多服务器场景。
基于以上原因生产环境建议使用 PostgreSQL, MySQL, and SQL Server. Django官方文档 Database setup. 云服务文档 Azure SDK for Python .
定义模型model
Django中的Model是python的类来源于“django.db.models.Model”。相关的类在 app目录下的 models.py文件里进行定义。在数据库中每一个Model自动给予编号字段名id。其他的字段作为类的属性存在。属性的类型源自django.db.models的类型包括CharField (limited text) , TextField (unlimited text)EmailField, URLField, IntegerField, DecimalField, BooleanField, DateTimeField, ForeignKey, ManyToMany等。(详见Django文档 Model field reference .)
每个字段都有属性定义如max_length. “blankTrue”代表该字段为可选项“nullTrue”代表可以没有数据。另外还有“choice”属性可以限制输入来源。
示例
在hello目录下的model.py文件中定义“LogMessage”类。 from django.db import models
from django.utils import timezoneclass LogMessage(models.Model):message models.CharField(max_length300)log_date models.DateTimeField(date logged)def __str__(self):Returns a string representation of a message.date timezone.localtime(self.log_date)return f{self.message} logged on {date.strftime(%A, %d %B, %Y at %X)}在模型中可以包含使用数据计算出返回值的方法。 models中通常包括__str__方法用于描述类和实例。
迁移数据库创建数据库 由于新创建了model需要更新数据库。在启动项目虚拟环境的Terminal中运行下面的命令。 python manage.py makemigrations
python manage.py migrate在hello/migrations目录下创建0001_initial.py文件。db.sqlite3数据库文件还不会检查。
通过model使用数据库
通过model和migrate机制可以通过models来管理数据。在本节中新建form页面进行注册。修改home页面显示上述信息。
建立log message页面输入数据
1在hello目录下app目录创建forms.py文件。代码如下代码目的创建一个form from django import forms
from hello.models import LogMessageclass LogMessageForm(forms.ModelForm):class Meta:model LogMessagefields (message,) # NOTE: the trailing comma is required2在hello/templates/hello中创建log_message.html文件。定义log_message页面信息。有输入框和按钮。
{% extends hello/layout.html %}
{% block title %}Log a message
{% endblock %}
{% block content %}form methodPOST classlog-form{% csrf_token %}{{ form.as_p }}button typesubmit classsave btn btn-defaultLog/button/form
{% endblock %}3更新CSS文件定义输入框的宽度
input[namemessage] {width: 80%;
}4hello/urls.py中增加新页面的路径
path(log/, views.log_message, namelog),5在hello/view.py中定义log_message子例程。定义log_message视图。完成两个任务post任务接收输入form.save增加时间戳保存到数据库message.save(). 没有输入时渲染log_message.html页面如else语句。
# Add these to existing imports at the top of the file:
from django.shortcuts import redirect
from hello.forms import LogMessageForm
from hello.models import LogMessage# Add this code elsewhere in the file:
def log_message(request):form LogMessageForm(request.POST or None)if request.method POST:if form.is_valid():message form.save(commitFalse)message.log_date datetime.now()message.save()return redirect(home)else:return render(request, hello/log_message.html, {form: form})6在home页面增加log_message的html元素。hello/templates/hello/layout.html, 在“navbar”内增加下面内容。在home后显示Log_message
One more step before youre ready to try everything out! In templates/hello/layout.html, add a link in the navbar div for the message logging page:
!-- Insert below the link to Home --
a href{% url log %} classnavbar-itemLog Message/a7运行程序结果如下。 8输入信息点击按钮。可以多输入几次。可以使用SQLite浏览器查看创建的数据。
9停止程序运行。完成后续home页面显示工作。
建立数据显示页面
10更改home.html
{% extends hello/layout.html %}
{% block title %}Home
{% endblock %}
{% block content %}h2Logged messages/h2{% if message_list %}table classmessage_listtheadtrthDate/ththTime/ththMessage/th/tr/theadtbody{% for message in message_list %}trtd{{ message.log_date | date:d M Y }}/tdtd{{ message.log_date | time:H:i:s }}/tdtd{{ message.message }}/td/tr{% endfor %}/tbody/table{% else %}pNo messages have been logged. Use the a href{% url log %}Log Message form/a./p{% endif %}
{% endblock %}11, 修改CSS文件 site.css
.message_list th,td {text-align: left;padding-right: 15px;
}12修改Views.py 导入相关模块。
from django.views.generic import ListView13, views.py中创建HomeListView类
# Remove the old home function if you want; its no longer usedclass HomeListView(ListView):Renders the home page, with a list of all messages.model LogMessagedef get_context_data(self, **kwargs):context super(HomeListView, self).get_context_data(**kwargs)return context14修改hello/urls.py引入数据model
from hello.models import LogMessage15, urls.py 中查询5个历史数据。
home_list_view views.HomeListView.as_view(querysetLogMessage.objects.order_by(-log_date)[:5], # :5 limits the results to the five most recentcontext_object_namemessage_list,template_namehello/home.html,
)16还是在同一个文件中修改path ,更改为home_list_view。不再使用原来的Hometemplate. # Replace the existing path for path(, home_list_view, namehome),17, 运行检查结果。 遇到的小问题
home.html文件中VSCODE自动将几行放到一行。为了正确换行增加注释!--demo--来强制分行。
小结model.py, form.py *.html, site.css, urls.py 为相关变化的文件。