以下学习 朔宁夫 基于pycharm的网站开发课程笔记。
富文本:
models: content = models.TextField(verbose_name="content")
或者 content = RichTestUploadingField(default="", verbose_name="content")
setting: installed_app: "ckeditor", "ckeditor_uploader", # 富文本编辑器 富文本上传工具
CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'height': 300, 'width': 800 } }
CKEDITOR_UPLOAD_PATH = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
图片:
models: content = models.ImageField(upload_to='b_i', verbose_name='i') # 会找media路径、创建上传的文件
setting: MEDIA_ROOT = os.path.join(BASE_DIR, 'static')
演示:
一个图文博客:
架构:
主页+详情页。模型:blog。视图类:展示目录+展示详情。
实现:
0 准备富文本工具,资源路径。
INSTALLED_APPS = [
'ckeditor',
'ckeditor_uploader',
]
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'full',
'height': 300,
'width': 800
}
}
CKEDITOR_UPLOAD_PATH = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'static')
1 创建模型。admin注册。后台添加测试数据。
from django.db import models
from ckeditor_uploader.fields import RichTextUploadingField
from ckeditor.fields import RichTextField
class Blog(models.Model):
title = models.CharField(max_length=32, unique=False, verbose_name='title')
abstract = RichTextUploadingField(max_length=64, verbose_name='abstract')
content = RichTextField(default='', verbose_name='content')
img = models.ImageField(upload_to='blog_img', verbose_name='img', blank=True)
class Meta:
db_table = 'Blogs'
verbose_name = 'a blog_app'
verbose_name_plural = 'blogs'
def __str__(self):
return f"{self.pk}__{self.title}"
@classmethod
def get_one(cls, pk):
try:
return cls.objects.get(pk=int(pk))
except cls.DoesNotExist:
return None
2 视图类
from django.shortcuts import render
from django.views import View
from blog_app.models import Blog
class BlogHome(View):
def get(self, request):
blogs = Blog.objects.all()
return render(self.request, 'bloghome.html', locals())
class BlogDetail(View):
def get(self, request, blog_id):
blog = Blog.get_one(pk=blog_id)
return render(self.request, 'blogdetail.html', locals())
3 templates
4 urls