djangoNotes

学员管理



en">

    UTF-8">
    Title
    stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css">
    stylesheet" href="/static/plugins/font-awesome/css/font-awesome.css">
    




<div class="container">
    <div style="padding: 20px 0;">

        #" id="addBtn" class="btn btn-primary ">添加
        #" class="btn btn-danger">删除
    div>

    <div>
        class="table table-bordered table-striped">
            tb">
            {% for row in stu_list %}
                {{ row.id }}">
                    
            {% endfor %}
            
ID 姓名 年龄 性别 班级 操作
nid">{{ row.id }} user">{{ row.username }} age">{{ row.age }} gender">{{ row.gender }} cls_id" cid="{{ row.cs_id }}">{{ row.cs.title }} class="glyphicon glyphicon-remove icon del-row"> class="fa fa-pencil-square-o icon edit-row">
div> div> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header">

class="modal-title" id="myModalLabel">创建学生

div> <div class="modal-body">
fm" class="form-horizontal"> <div class="form-group"> <div class="col-sm-10"> text" class="form-control" name="username" placeholder="姓名"> div> div> <div class="form-group"> <div class="col-sm-10"> text" class="form-control" name="age" placeholder="年龄"> div> div> <div class="form-group"> <div class="col-sm-10"> div> div> <div class="form-group"> <div class="col-sm-10"> div> div>
div> <div class="modal-footer"> <span id="errorMsg" style="color: red">span> div> div> div> div> <div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="alert alert-danger" role="alert">

删除学生信息?

<div>text " style="display: none" id="delNid">div> <div> div> div> div> div> <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header">

class="modal-title" id="myModalLabel">编辑学生

div> <div class="modal-body">
fm" class="form-horizontal"> text" name="nid" style="display: none"/> <div class="form-group"> <div class="col-sm-10"> text" class="form-control" name="user" placeholder="姓名"> div> div> <div class="form-group"> <div class="col-sm-10"> text" class="form-control" name="age" placeholder="年龄"> div> div> <div class="form-group"> <div class="col-sm-10"> div> div> <div class="form-group"> <div class="col-sm-10"> div> div>
div> <div class="modal-footer"> <span id="errorMsg" style="color: red">span> div> div> div> div>
student.html


from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from app01 import models
import json


def student(request):
    cla_list = models.Classes.objects.all()
    stu_list = models.Student.objects.all()
    return render(request , 'student.html' , {'stu_list': stu_list , 'cla_list': cla_list})


def add_student(request):
    response = {'status': True , 'message': None , 'data': None}
    try:
        u = request.POST.get('username')
        a = request.POST.get('age')
        g = request.POST.get('gender')
        c = request.POST.get('cls_id')

        obj = models.Student.objects.create(
            username=u ,
            age=a ,
            gender=g ,
            cs_id=c ,
        )

        response['data'] = obj.id

    except Exception as e:
        response['status'] = False
        response['message'] = '用户输入错误'

    result = json.dumps(response)
    return HttpResponse(result)


def del_student(request):
    ret = {'status': True}
    try:
        nid = request.GET.get('nid')
        models.Student.objects.filter(id=nid).delete()
    except Exception as e:
        ret['status'] = False
    return HttpResponse(json.dumps(ret))


def edit_student(request):
    response = {'code': 1000 , 'message': None}
    try:
        nid = request.POST.get('nid')
        u = request.POST.get('user')
        a = request.POST.get('age')
        g = request.POST.get('gender')
        c = request.POST.get('cls_id')
        models.Student.objects.filter(id=nid).update(
            username=u ,
            age=a ,
            gender=g ,
            cs_id=c ,
        )
    except Exception as e:
        response['code']=1001
        response['message']=str(e)
    return HttpResponse(json.dumps(response))
views.py

paging

分页组件
         a.内置
         b.扩展
         c.自定义

f1.html


en">

    UTF-8">
    Title


{% csrf_token %}
fm" action="/f1.html/" method="post">

{{ obj.user }}{{ obj.errors.user.0 }}

{{ obj.pwd }}{{ obj.errors.pwd.0 }}

{{ obj.age }}{{ obj.errors.age.0 }}

{{ obj.email }}{{ obj.errors.email.0 }}

submit" value="提交"/>

index1.html en"> UTF-8"> Title
    {% for user in user_list %}
  • {{ user.name }}-{{ user.age }}
  • {% endfor %}
{#边界问题#} /index.html?p={{ prev_pager }}">上一页 /index.html?p={{ next_pager }}">下一页 index1.html en"> UTF-8"> Title
    {% for user in posts.object_list %}
  • {{ user.name }}-{{ user.age }}
  • {% endfor %}
{% include 'include/pager.html' %} index2.html en"> UTF-8"> Title stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css">
    {% for row in data %}
  • {{ row.name }}-{{ row.age }}
  • {% endfor %}
{% for i in page_obj.pager_num_rang%} /index2.html?p={{ i }}">{{ i }} {% endfor %}
    class="pagination pagination-sm"> {{ page_obj.page_str|safe }}
templates
from django.shortcuts import render
from django.core.paginator import Paginator , EmptyPage , PageNotAnInteger

# Create your views here.

USER_LIST = []
for i in range(1 , 666):
    temp = {'name': 'root' + str(i) , 'age': i}
    USER_LIST.append(temp)


def index(request):
    per_page_count = 10
    current_page = request.GET.get('p')
    current_page = int(current_page)
    start = (current_page - 1) * per_page_count
    end = current_page * per_page_count
    data = USER_LIST[start:end]

    prev_pager = current_page - 1
    next_pager = current_page + 1

    if current_page <= 1:
        prev_pager = 1

    return render(request , 'index.html' , {
        'user_list': data ,
        'current_page': current_page ,
        'prev_pager': prev_pager ,
        'next_pager': next_pager ,
    })


class CustomPaginator(Paginator):
    def __init__(self , current_page , per_pager_num , *args , **kwargs):
        # 当前页
        self.current_page = int(current_page)
        # 最多显示的页码数量11
        self.per_page_num = int(per_pager_num)
        super(CustomPaginator , self).__init__(*args , **kwargs)

    def pager_num_rang(self):
        # 总页数
        if self.num_pages < self.per_page_num:
            return range(1 , self.num_pages + 1)

        # 总页数特别多 5
        part = int(self.per_page_num / 2)

        if self.current_page <= part:
            return range(1 , self.per_page_num + 1)

        if (self.current_page + part) > self.num_pages:
            return range(self.num_pages - self.per_page_num + 1 , self.num_pages + 1)

        return range(self.current_page - part , self.current_page + part + 1)


def index1(request):
    # 全部数据:USER_LIST,==》得出共有多少条数据
    # per_page: 每页显示条目数量
    # count:    数据总个数
    # num_pages:总页数
    # page_range:总页数的索引范围,如: (1,10),(1,200)
    # page:     page对象(是否具有下一页;是否具有上一页;)
    current_page = request.GET.get('p')
    # Paginator对象
    paginator = CustomPaginator(current_page , 7 , USER_LIST , 10)
    try:
        # Page 对象
        posts = paginator.page(current_page)
        # has_next              是否有下一页
        # next_page_number      下一页页码
        # has_previous          是否有上一页
        # previous_page_number  上一页页码
        # object_list           分页之后的数据列表
        # number                当前页
        # paginator             paginator对象
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)
    return render(request , 'index1.html' , {'posts': posts})


def index2(request):
    from app01.pager import Pagination
    current_page = request.GET.get('p')
    page_obj = Pagination(666 , current_page)

    data_list = USER_LIST[page_obj.start():page_obj.end()]
    return render(request , 'index2.html' , {'data': data_list , 'page_obj': page_obj})
views.py


class Pagination(object):
    def __init__(self , totalCount , currentPage , perPageNum=10 , maxPageNum=6):
        # 数据总个数
        self.total_count = totalCount
        # 当前页
        try:
            v = int(currentPage)
            if v < 0:
                v = 1
            self.current_page = v
        except Exception as e:
            self.current_page = 1
        # 每页显示的行数
        self.per_page_item_num = perPageNum
        # 最多显示页面
        self.max_page_num = maxPageNum

    def start(self):
        return (self.current_page - 1) * self.per_page_item_num

    def end(self):
        return self.current_page * self.per_page_item_num

    @property
    def num_pages(self):
        '''
        总页数
        :return:
        '''
        # 666
        # 10
        a , b = divmod(self.total_count , self.per_page_item_num)
        if b == 0:
            return a
        return a + 1

    def pager_num_rang(self):
        # 总页数
        if self.num_pages < self.max_page_num:
            return range(1 , self.num_pages + 1)
        # 总页数特别多 5
        part = int(self.max_page_num / 2)
        if self.current_page <= part:
            return range(1 , self.max_page_num + 1)
        if (self.current_page + part) > self.num_pages:
            return range(self.num_pages - self.max_page_num + 1 , self.num_pages + 1)
        return range(self.current_page - part , self.current_page + part + 1)

    def page_str(self):
        page_list = []
        first = '
  • /index2.html?p=1">首页
  • ' page_list.append(first) if self.current_page == 1: prev = "
  • 上一页
  • " else: prev = "
  • 上一页
  • " % (self.current_page - 1 ,) page_list.append(prev) for i in self.pager_num_rang(): if i == self.current_page: temp = "
  • %s
  • " % (i , i) else: temp = "
  • %s
  • " % (i , i) page_list.append(temp) if self.current_page == self.num_pages: nex = "
  • 下一页
  • " else: nex = "
  • 下一页
  • " % (self.current_page + 1) page_list.append(nex) last = '
  • /index2.html?p=%s">尾页
  • ' % (self.num_pages) page_list.append(last) return ''.join(page_list)
    pager.py


    Form

    from django.http import HttpResponse
    from django.shortcuts import render
    from django.shortcuts import redirect
    from django import forms
    from django.forms import fields
    
    
    # Create your views here.
    
    class F1Form(forms.Form):
        user = fields.CharField(
            max_length=18 ,
            min_length=6 ,
            required=True ,
            error_messages={
                'required': '用户名不能为空',
                'max_length': '太长了',
                'min_length': '太短了',
            }
        )
        pwd = fields.CharField(min_length=32 , required=True)
        age = fields.IntegerField(
            required=True ,
            error_messages={
                'required': '年龄不能为空',
                'invalid': '必须为数字',
    
            }
        )
        email = fields.EmailField(
            required=True ,
            min_length=8 ,
            error_messages={
                'required': '邮箱不能为空',
                'invalid': '邮箱格式错误',
            }
        )
    
    
    def f1(request):
        if request.method == 'GET':
            obj=F1Form()
            return render(request , 'f1.html',{'obj':obj})
        else:
            # u = request.POST.get('user')#不能为空,长度6-18
            # p = request.POST.get('pwd')#不能为空,长度32
            # e = request.POST.get('email')#不能为空,邮箱格式
            # a = request.POST.get('age')#不能为空,数字类型
            # 1、检查是否为空
            # 2、检查格式是否正确
    
            obj = F1Form(request.POST)
            # 是否全部验证成功
            if obj.is_valid():
                # 用户提交的数据
                print('验证成功' , obj.cleaned_data)
                return redirect('http://www.xiaohuar.com')
            else:
                print('验证失败' , obj.errors)
                return render(request , 'f1.html' , {'obj': obj})
    
    views.py
    
    en">
    
        UTF-8">
        Title
    
    
    {% csrf_token %}
    
    fm" action="/f1.html/" method="post">

    {{ obj.user }}{{ obj.errors.user.0 }}

    {{ obj.pwd }}{{ obj.errors.pwd.0 }}

    {{ obj.age }}{{ obj.errors.age.0 }}

    {{ obj.email }}{{ obj.errors.email.0 }}

    submit" value="提交"/>

    f1.html
    作用:验证+(生成HTML+保存上次提交的数据)
             使用:
                 1、创建类
                 2、创建字段()
                 3、验证用户输入:
                     obj=Form(request.POST,request.FILES)
                         if obj.is_valid():
                             obj.cleaned_data
                         else:
                             obj.errors
                 4、clean_字段
    
                 5、clean()  _post_clean()
    
                 PS:__all__ 整体错误信息

    1.form类的运行顺序是init,clean,validte,save
    其中clean和validate会在form.is_valid()方法中被先后调用。(这里留有一个疑问,结构完全相同的两个form,但是一个为先验证后clean,另一个先clean后验证。原因不明。)
    这里https://docs.djangoproject.com/en/dev/ref/forms/validation/给的是先验证后clean
    2.cleaned_data中的值类型与字段定义的Field类型一致。
    如果字段定义charfield,那么clean方法返回的cleaned_data中对应的字段值就是字符型,
    定义为ModelChoiceField,则cleaned_data中字段值是某个model实例。
    定义为ModelMultipleChoiceField,则cleaned_data中字段值是个model实例list。
    3.clean等步骤遇到的异常:Exception Value: argument of type 'NoneType' is not iterable.
    可能是cleaned_data中某个字段值应该是个列表,实际上却是空值。
    4.ModelForm的Meta类中定义的fields
    默认的Field是Model中定义的Field,如需更改,可在Form类内以同名字段覆盖,比如自定义widget和required属性等。
    不管字段在form中怎么自定义,cleaned_data中对应的值都必须按照model中定义的字段类型取值,否则校验不通过或保存时报错。
    暂时记这几条,form还可以重写init、save方法,并且可以自定义方法。如果对这几个东西不懂,想办法找例子读一遍就懂了。
    ※※※ clean方法重写时一定不要忘了return cleaned_data ※※※
    补充:
    5.form的四种初始化方式
    ①实例化oneform(initial={'onefield':value})
    ②定义字段时给初始化值oneformfield = forms.CharField(initial=value)
    ③重写Form类的__init__()方法:self.fields['onefield'].initial = value
    ④当给form传参instanse(即oneform(instanse=onemodel_instance))时,前三种初始化方法会全部失效,即使重写__init__时,先调用父类的__init__再使用方法③,仍然无效(不是很爽)。
    这时想重新初始化字段值只能在__init__()里 self.initial['title'] = value,直接对Form类的initial属性字典赋值。

    序列化


             JavaScript:
                 JSON.parse()
                 JSON.stringify()
            
             Django:
                 json.dumps()
                 json.loads()
                 问题:
                     serialize : model.TB.objects.all()
                     json : list(model.TB.objects.values())
                     json : list(model.TB.objects.value_list())

    文件上传

    from django.http import HttpResponse
    from django.shortcuts import render
    from django.forms import fields
    from django import forms
    
    
    class UploadForm(forms.Form):
        user = fields.CharField()
        img = fields.FileField()
    
    
    # Create your views here.
    def upload(request):
        if request.method == "GET":
            return render(request , 'upload.html')
    
        else:
            # obj=UploadForm(request.POST,request.FILES)
            # if obj.is_valid():
            #     user=obj.cleaned_data['user']
            #     img=obj.cleaned_data['img']
    
            img = request.FILES.get('img')
            # img是对象(文件大小,文件名称,文件内容。。。)
            user = request.FILES.get('img')
    
            f = open(img.name , 'wb')
            for line in img.chunks():
                f.write(line)
            f.close()
            return HttpResponse('ok')
    
    
    en">
    
        UTF-8">
        Title
    
    
    
    
    /upload.html" method="post" enctype="multipart/form-data"> {% csrf_token %} text" name="user"> <div style="position:relative"> ">upload file" name="img" style="opacity: 0;position: absolute;top: 0;left: 0"> div> submit" value="提交">

    你可能感兴趣的:(djangoNotes)