一、删除功能
1.编辑urls.py配置文件
urlpatterns = [
# 文章删除
url(r'^del_art/', views.del_art, name='del_art'),
url(r'^del_art_id/(\d+)/', views.del_art_id, name='del_art_id'),
2.删除文章功能
方法1:
from django.urls import reverse
from article.models import Article
def del_art(request):
if request.method == 'GET':
id = request.GET.get('id')
# 查询需要删除的文章,并调用delete()进行删除
Article.objects.filter(pk=id).delete()
return HttpResponseRedirect(reverse('art:art_list'))
方法2:
from django.urls import reverse
from article.models import Article
def del_art_id(request, id):
if request.method == 'GET':
# 查询文章并删除
Article.objects.filter(pk=id).delete()
return HttpResponseRedirect(reverse('art:art_list'))
二、修改功能
1.编辑urls.py配置文件
urlpatterns = [
# 文章编辑
url(r'^edit_art/(\d+)/', views.edit_art, name='edit_art'),
]
2.新建form表单
from django import forms
class EditArtForm(forms.Form):
# required = True 表示必填项
# min_length 表示最小长度
title = forms.CharField(min_length=5, required=True,
error_messages={
'required': '文章标题是必填项',
'min_length': '文章标题不能少于5个字符',
})
desc = forms.CharField(min_length=20, required=True,
error_messages={
'required': '文章描述必须填写',
'min_length': '文章描述不能少于20字符',
})
content = forms.CharField(required=True,
error_messages={
'required': '文章内容必须填写',
})
icon = forms.ImageField(required=False)
3.修改文章功能
from article.Artform import EditArtForm
from article.models import Article
def edit_art(request, id):
if request.method == 'GET':
# 获取编辑文章对象
article = Article.objects.filter(pk=id).first()
return render(request, 'add_article.html', {'article': article})
if request.method == 'POST':
form = EditArtForm(request.POST, request.FILES)
if form.is_valid():
title = form.cleaned_data['title']
desc = form.cleaned_data['desc']
content = form.cleaned_data['content']
icon = form.cleaned_data['icon']
article = Article.objects.filter(pk=id).first()
article.title =title
article.desc = desc
article.content = content
if icon:
article.icon = icon
article.save()
return HttpResponseRedirect(reverse('art:art_list'))
else:
article = Article.objects.filter(pk=id).first()
return render(request, 'add_article.html', {'form': form, 'article': article})
三、富文本编辑器
1.在settings.py中配置如下参数
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
2.页面中加载富文本编辑器
{% block js %}
{% load static %}
{% endblock %}
3.Django过滤器
1.safe:渲染标签的样式
{{ content_h2 | safe }}
2.upper:将所有的单词都大写
{{ name | upper }}
3.lower:将所有的单词都小写
{{ name | lower }}
4.capfirst:将所有的单词首字母大写
{{ name | capfirst }}
5.first:获取python变量中的第一个字符
{{ name | first }}
6.last:获取python变量中的最后一个字符
{{ name | last }}
四、日志文件
1.日志logging模块
logging模块可以收集记录错误,警告等调试信息,在程序中可以捕获这些信息,甚至可以将错误的重要信息等通过邮件发送给开发者。
2.logging的组成
Loggers:日志系统的入口,可以向它写入需要处理的消息
Handlers:Handler决定如何处理logger中的每条消息,它表示一个特定的日志行为
Formatters:日志记录需要转换成的文本格式
3.在settings.py文件中配置LOGGING日志信息
LOG_PATH = os.path.join(BASE_DIR, 'log')
LOGGING = {
# 必须设置为1
'version': 1,
# 禁止日志,默认值为True
'disable_existing_loggers': False,
# 格式化
'formatters': {
'default': {
'format': '%(message)s'
}
},
# logger接收日志
'loggers': {
'': {
'handlers': ['console'],
'level': 'INFO',
}
},
# handlers处理日志
'handlers': {
'console': {
'level': 'INFO',
'filename': '%s/day08log.log' % LOG_PATH,
'formatter': 'default',
'class': 'logging.handlers.RotatingFileHandler',
'maxBytes': 5 * 1024 * 1024
}
}
}
4.定义日志处理中间件
import time
import logging
from django.utils.deprecation import MiddlewareMixin
# 获取logger
log = logging.getLogger(__name__)
class LogMiddleware(MiddlewareMixin):
def process_request(self, request):
# 绑定在request上的一个属性,表示访问的时间
request.init_time = time.time()
def process_response(self, request, response):
# 请求URL耗时时间
count_time = time.time() - request.init_time
# 响应状态码
code = response.status_code
# 请求地址
path = request.path
# 请求方式
method = request.method
# 响应内容
content = response.content
# 需要打印的日志信息
log_str = '%s %s %s %s %s' % (path, method, code,
count_time, content)
# 交给logger处理日志
log.info(log_str)
return response