当接收一个HttpRequest对象时, django会自上而下地寻找urlpatterns进行匹配
起点就是ROOT_URLCONF中设置的路径
urlpatterns
它是 django.urls.path() 和(或) django.urls.re_path() 实例的序列
urlpatterns = [path('polls/', include("polls.urls")),path('admin/', admin.site.urls),
]
URL匹配
变量匹配
path('/vote/', views.vote, name='vote'),
<>包围int代表数据类型, 也可以是str/正则匹配
其实是封装re正则表达式模块
^表示开头, $表示结尾. 防止上级路径捕获次级路径的情况
import repath = "5/vote/"
m = re.match(r'^(?P\d+)/vote/$', path)
print(m.group("question_id"))
re_path(r'^(?P\d+)/vote/$', views.vote, name='vote')
include
include可以将其他urlconf添加到当前的urlpatterns序列当中.
获取当前url的路径
request.path
获取当前请求对象的method
request.method
获取当前请求体
request.body
获取POST携带的data参数
data_dict = request.POST
choice = request.POST['choice']
获取GET携带的params参数
params_dict = request.GET
获取当前请求的session
reqeust.session
获取当前请求的cookie
cookie_dict = request.COOKIES
获取当前的域名
request.get_host()
获取当前传输数据类型
request.content_type
模板
return render(request, 'polls/results.html', {'question': question})
返回字符串
return HttpResponse('test')
返回JSON格式的字符串
虽然本质和HttpResponse(json.dumps({})) 一致, 但是JsonResponse提供了更多的功能
from django.http import JsonResponsereturn JsonResponse({'choice': 2}, safe=False)
返回文件
from django.http import FileResponsedef file_test(request):filename = "views.py"with open("polls/views.py", "r", encoding="utf-8") as f:response = FileResponse(f.read())response['content-type'] = "application/octet-stream"response['content-disposition'] = f"attachment; filename={filename}"return response
返回异常
raise Http404()
HTTP协议请求方式
GET(查), POST(增), PUT(改), DELETE(删)
基于函数的视图
def index(request):"""request 就是作为参数传递进来的请求对象:param request::return: HttpResponse 处理完请求的返回对象"""latest_question_list = Question.objects.order_by('-pub_date')[:5]context = {'latest_question_list': latest_question_list,}return render(request, 'polls/index.html', context)
绑定url
path('', views.index, name='index'),
用函数实现restful api
def index_get(request):passdef index_post(request):passdef index_put(request):passdef index_delete(request):pass
基于类的视图
class IndexView(generic.TemplateView):template_name = "polls/index.html"def get_context_data(self, **kwargs):latest_question_list = Question.objects.order_by('-pub_date')[:5]context = {'latest_question_list': latest_question_list,}return context
绑定url
path('', views.IndexView.as_view(), name='index'),
用类实现restfulapi
只需要绑定一次path, 会根据HttpRequest.method自动选择相应的处理方法.
class IndexView(generic.View):def get(self, *args, **kwargs):passdef post(self, *args, **kwargs):passdef put(self, *args, **kwargs):passdef delete(self, *args, **kwargs):pass
https://hexo.io/themes/
创建虚拟环境
安装依赖
批量导出安装的第三方库
pip freeze >> requirements.txt
批量安装第三方库
pip install -r requirements.txt
前端框架最终都会转为HTML, CSS, JS的形式在浏览器中完成渲染
我们只要自定义静态资源中的内容九可以达到自动博客主题的目的
在settings中配置静态资源
templates
TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates','DIRS': [os.path.join(BASE_DIR, "templates")], // 添加模板所在目录路径'APP_DIRS': True,'OPTIONS': {'context_processors': ['django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],},},
] static
# http://127.0.0.1:8000/static/xxx.js
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),
]
在路由urls中配置静态资源访问url路径
urlpatterns = [path('admin/', admin.site.urls),
] + static(settings.STATIC_URL)
略
class Article(models.Model):title = models.CharField(max_length=200)text = models.TextField()url = models.CharField(max_length=200)update_time = models.DateTimeField(auto_now=True)create_time = models.DateTimeField(auto_now_add=True)class Meta:db_table = "article"def __str__(self):return f""
from django.shortcuts import render
from django.views.generic import TemplateView
from .models import Article
# Create your views here.
import mathclass IndexView(TemplateView):template_name = "index.html"def get(self, request, *args, **kwargs):article_list = Article.objects.order_by("-create_time")for article in article_list:article.pub_date = article.create_time.strftime("%m-%d").replace("-", "月")article.length = len(article.text)article.read_time = math.ceil(len(article.text)/180) if article.text else 0context = {"article_list": article_list}return self.render_to_response(context)
添加路由
path("", IndexView.as_view())
设计model
# 由于我们接下来要使用django自带的管理页面, 所以这里我们用了外键
class Category(models.Model):article = models.ForeignKey(Article, on_delete=models.CASCADE)name = models.CharField(max_length=200)slug = models.CharField(max_length=200)uri = models.CharField(max_length=200)
注册管理后台
django的管理后台提供了很多丰富的功能, 有兴趣的可以研究一下.
建议学完js之后直接上手学习vue前端框架, 收益更高一点.
from django.contrib import admin
from .models import Article, Category, Tag
# Register your models here.class CategoryInline(admin.TabularInline):model = Categoryclass TagInline(admin.TabularInline):model = Tagclass ArticleAdmin(admin.ModelAdmin):inlines = [CategoryInline, TagInline]list_display = ['title', 'create_time']admin.site.register(Article, ArticleAdmin) 修改模板index.html
略
修改视图
class IndexView(TemplateView):template_name = "index.html"def get(self, request, *args, **kwargs):article_list = Article.objects.order_by("-create_time")for article in article_list:article.pub_date = article.create_time.strftime("%m-%d").replace("-", "月")article.length = len(article.text)article.read_time = math.ceil(len(article.text)/180) if article.text else 0# 外键可以通过以下方式获取到集合article.categories = article.category_set.values()article.tags = article.tag_set.values()# cate_list = Category.objects.filter(article_id=article.id)context = {"article_list": article_list,}return self.render_to_response(context)
获取detail.html
安装markdown转html的第三方库和应用
# 将md文档转换为html文件
pip install markdown
增加路由
path("///", DetailView.as_view()),
修改模板detail.html
通过safe参数来声明当前是元素
{{ article.content|safe }}
修改视图
class DetailView(TemplateView):template_name = "detail.html"def get(self, request, *args, **kwargs):article = Article.objects.get(url=request.path)content = ""for line in article.text.split("\n"):content += line.strip(" ") if "```" in line else linecontent += "\n"article.content = markdown.markdown(content, extensions=['markdown.extensions.extra', # 转换标题, 字体等'markdown.extensions.codehilite', # 添加高亮功能'markdown.extensions.toc', # 将表单渲染为html document类型])context = {"article": article,}return self.render_to_response(context)
安装django-mdeditor
# md文档后台管理页面编译应用
pip install django-mdeditor
在settings当中添加应用
INSTALLED_APPS = ['mdeditor',...
]
修改model中文章内容字段类型
from mdeditor.fields import MDTextFieldtext = MDTextField()