【django】-filter&tag&分页orm基础操作&form验证
1、filter
- 自带的filter
<h1>django自带filter</h1> {{ navs|length }} -- 长度<br> {{ navs.0 }} -- 获取第一个元素<br> {{ navs|truncatechars:6 }} -- 包括...在内超过6个字符就省略后面的<br> {{ navs|truncatechars_html:6 }} -- innterText的内容...<br> {{ title|slice:"0:8"}} -- 切片<br> {{ navs|join:"="}} -- 拼接,如果是字符串则每个字符串中间用=号相连<br> {{ title |default:"管理员"}} -- 如果后台没有返回则显示默认参数<br> {{ cur_time|date:'Y/m/d H:i:s'}} -- 格式化时间<br> {{ nav|safe}} -- 如果返回的数据是标签格式,则渲染到页面上<br> {{ title|lower }} -- 小写<br> {{ title|upper }} -- 大写<br>
-
- 在html当中通过{{navs|length}}使用,实际是将navs传递给length函数
- {{navs|truncatechars:6}} navs是第一个参数 6是第二个参数
- 自定义filter、tag
- 创建demoTags.py
-
- 代码如下
from django import template # register变量必须这么定义 register = template.Library() # 自定义filter # filter最多支持2个参数,管道符左侧为第一个参数,冒号后为第二个参数 @register.filter def status_filter(x): if x == 1: return '成功' else: return '失败' # 自定义tag # simple_tag可以支持多个参数,通过空格进行分格即可 @register.simple_tag def test_simple_tag(x, y, z): return x + y + z
- 页面使用
- 在html中导入{% load demoTags %}
-
*********自定义filter********<br> {{ navs|status_filter }}<br> {{ status|status_filter }}<br> *********simple_tag_test*****<br> {% test_simple_tag 1 1 1 %}
- 代码如下
2、django分页
- views.py
from django.core.paginator import Paginator from django.shortcuts import render from . import models def index(request): print('index....') page = request.GET.get('page') print('页面传递过来的参数', page)
articles = models.Article.objects.all()
# 分页
# 创建 分页实例 articles是文章所有数据,第二个参数代表每页展示1条数据
page_obj = Paginator(articles, 1)
print("返回总条数:",page_obj.count)
print("返回总页数,一共分了多少页:",page_obj.num_pages)
# range可迭代代销,顾头不顾尾
print("页码列表 range对象:",page_obj.page_range)
for i in page_obj.page_range:
print(i)
# 获取第几页的数据集
page_data = page_obj.get_page(page)
# print(page_data.has_other_pages()) # 是否有上一页或下一页
# print(page_data.has_next()) # 是否有下一页
# print(page_data.has_previous()) # 是否有上一页
# print(page_data.next_page_number()) # 下一页页码值
# print(page_data.previous_page_number()) # 上一页页码值# print('起始:', page_data.start_index()) # 返回当前页起始的对象序号
# print('结束:', page_data.end_index()) # 返回当前页结束的对象序号
print("当前页:", page_data.number) # 当前页
return render(request, 'index.html', {'articles': page_data, 'page_obj': page_obj}) - index.html
{# 分页 #} <div> {% if articles.has_other_pages %} <div class="text-center mt-2 mt-sm-1 mt-md-0 mb-3 f-16"> {% if articles.has_previous %} <span class="text-secondary" title="当前页已经是首页"><a href="/articles?page={{ articles.previous_page_number }}">上一页</a></span> {% endif %} {% for num in page_obj.page_range %} {% if num == articles.number %} <span class="mx-2" style="background: #007bff"><a href="articles?page={{ num }}">{{ num }}</a></span> {% else %} <span class="mx-2"><a href="articles?page={{ num }}">{{ num }}</a></span> {% endif %} {% endfor %} {% if articles.has_next %} <a class="text-success" href="articles?page={{ articles.next_page_number }}">下一页</a> {% endif %} </div> {% endif %} </div>
3、orm基础操作
- 创建老师、学生表:models.py
# 多对多关系 class Student(models.Model): name = models.CharField(verbose_name='学生名字',max_length=50) age = models.IntegerField(verbose_name='年龄',default=1) class Meta: db_table = 'student' class Teacher(models.Model): name = models.CharField(verbose_name='老师名字', max_length=50) #多对多关系的建立 student = models.ManyToManyField(Student,verbose_name='学生') class Meta: db_table = 'teacher'
- 基本操作
# 多对多关系 teacher_obj = models.Teacher.objects.get(id=2) student_obj = models.Student.objects.get(id=3) # # 创建多对多关系 方法1 # teacher_obj.student.add(student_obj) # # 创建多对多关系 方法2 add 方法可以接收主键id # teacher_obj.student.add(3) # # 覆盖添加 # teacher_obj.student.set([4,5]) # 删除多对多关系 # 清楚老师对应的所有学生 批量操作 # teacher_obj.student.clear() # 制定学生进行删除,可以接收对象和主键id # teacher_obj.student.remove(student_obj) # teacher_obj.student.remove(2) # 查询多对多关系 # 正向查询 # # 获取这个老师,有哪些学生 # students = teacher_obj.student.all() # print("students:",students) # # 反向查询 # # 基于某个学生,去查这个学生有几个老师 # teachers = student_obj.teacher_set.all() # print("teachers:",teachers) # orm基础操作 # orm 返回的有两种数据类型 QuerySet object teachers = models.Teacher.objects.all() # print("teachers:",teachers) # name = teachers.values('name') # 过滤字段,获取我们希望获取的字段 # print(name) # # count = teachers.count() # 返回qs的个数 # print('count:',count) # # firstData = teachers.first() # print('firstData',firstData) # # value_name = teachers.values_list('name') # 只返回要过滤字段的value,不返回key # print('value_name',value_name) # teacher = models.Teacher.objects.get(id=1) # # print('teacher',teacher) # print('teacher.name:',teacher.name) # 过滤:orm的filter,即sql的where条件 # # 模糊查询 # teacher = models.Teacher.objects.filter(name__contains='师') # print(teacher.values('name')) # # teacher = models.Teacher.objects.filter(name__startswith='牛') # print(teacher.values('name')) # # teacher = models.Teacher.objects.filter(name__endswith='兄') # print(teacher.values('name')) # # teacher = models.Teacher.objects.filter(name__in=['大师兄']) # print(teacher.values('name')) # # 排除 # # 除了name为大师兄 其他都查出来 # teacher = models.Teacher.objects.exclude(name='大师兄') # print(teacher.values('name')) # 多条件查询 # # and # print(models.Teacher.objects.filter(id=1,name='牛牛').values('name')) # # # or # # 查询id=1 或者 name=大师兄 # # 导入 from django.db.models import Q # teacher = models.Teacher.objects.filter(Q(id=1) | Q(name='大师兄')) # print(teacher.values('name')) # and teacher = models.Teacher.objects.filter(Q(id=1) & Q(name='大师兄')) # 取反 teacher = models.Teacher.objects.filter(Q(id=1) & ~Q(name='大师兄')) print(teacher.values('name'))
4、forms验证(前端传过来的数据)
- 创建forms.py文件
- forms.py
from django import forms from django.core.exceptions import ValidationError from user import models # 第一步的验证 def test_phone(value): print('test_phone',3) if len(value) != 11: raise ValidationError('手机格式不正确') else: return value # Form class ArticleForm(forms.Form): # 字段名称要和提交的相同 title = forms.CharField(required=True, # 是否必填 max_length=10,# 最大10个字符 min_length=5, # 最小5个字符 error_messages={ # 错误信息提示 'required': 'title未填', 'max_length':'最大10个字符', 'min_length':'最小5个字符', }) phone = forms.CharField(required=True, # 是否必填 validators=[test_phone], error_messages={ # 错误信息提示 'required': '手机号未填', }) # forms中存在钩子函数 # 第三步:进行全部数据验证 def clean(self): # 通过self.cleaned_data 获取所有数据 print("clean",1) return self.cleaned_data # 第二步:针对 个别字段进行验证 def clean_phone(self): print("clean_phone", 2) return self.cleaned_data.get('phone') # model + form def test_name(value): if value == 'dsx': raise ValidationError('姓名不存在。') else: return value # ModelForm class StudentForm(forms.ModelForm): # 当你觉得model写的验证规则不符合你的要求,可以像forms.Form 一样进行验证 name = forms.CharField(validators=[test_name]) class Meta: model = models.Student # 创建类变量和model建立映射关系 # fields = '__all__' # 验证全部字段 # fields = ['name'] # 显示指定列验证 只有指定的验证的字段才会出现在cleaned_data中 exclude = ['age'] # 排除了就不会出现在cleaned_data中 def clean(self): if self.cleaned_data.get('name') == 'ssz': raise ValidationError('姓名是射手座') else: return self.cleaned_data # 单个字段验证,必须要争在form中有些这个 字段 def clean_name(self): if self.cleaned_data.get('name') == 'nhy': raise ValidationError('姓名是nhy') else: return self.cleaned_data.get('name')
- views.py:Form验证
from django.shortcuts import render,HttpResponse from user.forms import ArticleForm def article(request): #创建文章 if request.method=='GET': return render(request,'post.html') else: # 实例化form验证器,接收post传过来的数据 articleObj = ArticleForm(request.POST) # 验证是否通过 true false print(articleObj.is_valid()) f = articleObj.is_valid() if f: # 验证通过的数据 存在了一个叫cleaned_data的dict中 print(articleObj.cleaned_data) msg='成功' else: #拿到错误信息 print("错误信息:",articleObj.errors) # 通过dict方式取信息 print("错误信息:", articleObj.errors.get_json_data()) # msg = articleObj.errors.get_json_data().get('title')[0].get('message') # msg = articleObj.errors msg='验证失败' return HttpResponse(msg)
- urls.py
path('post',views.article),
- urls.py
- views.py:ModelForm验证
-
from django.shortcuts import render,HttpResponse from user.forms import StudentForm
def student(requests): if requests.method == 'GET': return render(requests, 'student.html') else: student_obj = StudentForm(requests.POST) f = student_obj.is_valid() if f: print('cleaned Data',student_obj.cleaned_data) else: print('error',student_obj.errors) return HttpResponse('ok') - urls.py
path('student',views.student),
-
- 页面输入不合法的参考,则会给出提示信息