Django 博客教程笔记(二)

分页使用

# views.py
article_list = Article.objects.all() 
paginator = Paginator(article_list, 10) // 创建分页对象
try:
    page = int(request.Get.get('page',1))
    article_list = paginator.page(page) // 获得当前页数据
except (EmptyPage, InvalidPage, PageNotAnInterger) :
    article_list = paginator.page(1)
#
# 模板中
for tag in article.tag.all // 多对多
for comment in article.comment_set.all // 一对多
article.publisher_date | date:'Y-m-d'
#
# 模板中分页

自定义 manger 管理器

对于 select date_format() 这种 sql 语句只能通过 raw 或者 execute 方式
但是 raw  的 % 要用 %% 转义,同时 raw 必须包含主键
更优雅的方式是:自定义 manager 管理器:
# models.py
class ArticleManager(models.Manager):
    # 新增一个数据处理的方法,此处为此方式
    # 改变原有的 queryset
    def distinct_data(self):
        distinct_data_list = []
        datas = self.values('publisher_date')
        for data in datas:
            date = data['publisher_date'].strftime('%Y-%m docs')
            if date not in distinct_data_list:
                distinct_data_list.append(date)
        return distinct_data_list

class Article(models.Model):
    objects = ArticleManager()
#
# views.py
print(Article.objects.distinct_data()
# index.html
{{ archive|slice:':4' }}
# views.py
year = request.GET.get('year')
month = request.GET.get('month')
Article.objects.filter(publisher_date__icontains=year+'-'+month)
# archive.html
{{ request.GET.year }}

重构

  • 把 category_list 和 archive_list 放到了 global_settings()
  • 重构 page : getPage(request, article_list) , include 'pagination.html'
  • pagination.html 中 加入分页参数的判断
  • 评论排行
# 
comment_list = Comment.objects.values('articles').annotate(c_count=Count('article')).order_by('-c_count')
# 
article_list = [Article.objects.get(pk=comment['article']) for comment in comment_list]
  • global_settings() 函数中 return locals()

自定义过滤器

# app 目录下创建 templatetags 文件夹 ,myfilter.py 文件
# -*- coding: utf-8 -*-
from django import template
register = template.Library()

# 定义一个将日期中的月份转换为大写的过滤器,如8转换为八
@register.filter
def month_to_upper(key):
        return ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'][key.month-1]

# 注册过滤器
# register.filter('month_to_upper', month_to_upper)
#
# 
{% load myfilter %}

评论

# 获取评论信息
        comments = Comment.objects.filter(article=article).order_by('id')
        comment_list = []
        for comment in comments:
            for item in comment_list:
                if not hasattr(item, 'children_comment'):
                    setattr(item, 'children_comment', [])
                if comment.pid == item:
                    item.children_comment.append(comment)
                    break
            if comment.pid is None:
                comment_list.append(comment)

# forms.py 中评论表单
class CommentForm(forms.Form):
    '''
    评论表单
    '''
    author = forms.CharField(widget=forms.TextInput(attrs={"id": "author", "class": "comment_input",
                                                           "required": "required","size": "25", "tabindex": "1"}),
                              max_length=50,error_messages={"required":"username不能为空",})
# views.py 中评论表单
        comment_form = CommentForm({'author': request.user.username,
                                    'email': request.user.email,
                                    'url': request.user.url,
                                    'article': id} if request.user.is_authenticated() else{'article': id})
# article.html
{{ comment_form.author }}
# views.py
if comment_form.is_valid()
Comment.objects.create()
#
# 绕过 csrf_token
@csrf_exemp

注册,登录,注销

  • 注册
class RegForm(forms.Form):
    '''
    注册表单
    '''
    username = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Username", "required": "required",}),
                              max_length=50,error_messages={"required": "username不能为空",})
# 获取表单对象
reg_form = RegForm(request.POST)
# 模板页面
{{ reg_form.username }}
# 获取来源页

# do_reg
password=make_password(reg_form.cleaned_data["password"]),)
  • 登录
user.backend = 'django.contrib.auth.backends.ModelBackend' # 指定默认的登录验证方式 
# 验证用户
user = authenticate(username=username, password=password)
login(request, user)                
return redirect(request.POST.get('source_url'))
  • 注销
logout(request)
  • 判断是否登录
request.user.is_authenticated()
#  模板中
{% if not request.user.is_authenticated %}

你可能感兴趣的:(Django 博客教程笔记(二))