zoukankan      html  css  js  c++  java
  • crm-1

    1.crm

      客户关系管理系统 :1.业务逻辑部分  2.权限插件

    2.forms组件之modelform

      modelform就是model+form ,form根据model的字段生成标签 ,校验信息以及记录的功能 ,一步提交所有数据功能

      使用方法:

        1)定义个类继承forms.modelform

        2)定义哪些字段生成标签fields = '__all__'所有标签

        3)定义错误信息以字典的格式

        4)重写init方法使用插件给标签更新属性

        5)实例化modelform时候 ,如果是对已有对象进行修改需要添加 instance = 已有对象这个参数 ,指定修改对象生成前段标签

        6)is_valid()通过后可以直接使用 obj.save()提交数据

    ####model
    class Dep(models.Model):
        name = models.CharField(max_length=32, verbose_name='部门')           #前端的显示label等于verbose_name
        desc = models.CharField(max_length=128, verbose_name='描述')
    
    
    
    ####view
    from django import forms
    
    # Create your views here.
    class DepForm(forms.ModelForm):
        # 也可以重写modle中已有的字段!
        # name = forms.CharField()
        class Meta:
            model = models.Dep
            fields = '__all__'
         #exclude = []      #排除字段
            error_messages = {            #给每个字段定义错误提示
                'name':{
                    'required': '必填项'
                },
                'desc':{
                    'required': '必填项'
                }
            }
    
        def __init__(self, *args, **kwargs):            #定义字段生成标签的属性!
            super(DepForm, self).__init__(*args, **kwargs)
            for field in self.fields.values():
                field.widget.attrs.update({'class': 'form-control'})
    
    
    def depadd(request):
        form_obj = DepForm()
        if request.method == 'POST':
            form_obj = DepForm(request.POST)
            if form_obj.is_valid():
                form_obj.save()    
                return redirect(reverse('crm:deplist'))
            print()
        return render(request, 'depadd-edit.html', {'form_obj': form_obj})
    
    def depedit(request, edit_id):
    obj = models.Dep.objects.filter(pk=edit_id).first()
    form_obj = DepForm(instance=obj)
    if request.method == 'POST':
    form_obj = DepForm(request.POST, instance=obj)
    if form_obj.is_valid():
    form_obj.save()
    return redirect(reverse('crm:deplist'))
    return render(request, 'depadd-edit.html', {'form_obj': form_obj})
    
    

    3.优化删除功能使用alter弹窗提示

       异步思想: 删除点击后弹出框提示是否删除 ,如果删除前端移除该行记录 ,数据库中删除该条记录 (sweetalter + ajax + 前端js删除父级标签)

    4.密码加密处理

      用户输入两次密码 ,如果成功 ,直接使用md5加密存放在数据库中 。所以用户输入的密码永远先做md5的处理   

      url部分

    ###url
    from django.conf.urls import url, include
    from django.contrib import admin
    from crm.view import user, dep
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^user/list/', user.userlist, name='userlist'),
        url(r'^user/add/', user.useradd, name='useradd'),
        url(r'^user/edit/(d+)/', user.useredit, name='useredit'),
        url(r'^user/del/(d+)/', user.userdel, name='userdel'),
    
        url(r'^dep/list/', dep.deplist, name='deplist'),
        url(r'^dep/add/', dep.depadd, name='depadd'),
        url(r'^dep/edit/(d+)/', dep.depedit, name='depedit'),
        url(r'^dep/del/(d+)/', dep.depdel, name='depdel'),
    
    ]
    View Code

      view部分

    ###dep-view
    from django.shortcuts import render, reverse, redirect, HttpResponse
    from crm import models
    from django import forms
    
    
    # Create your views here.
    class DepForm(forms.ModelForm):
        # 也可以重写modle中已有的字段!
        # name = forms.CharField()
        class Meta:
            model = models.Dep
            fields = '__all__'
            error_messages = {
                'name': {
                    'required': '必填项'
                },
                'desc': {
                    'required': '必填项'
                }
            }
    
        def __init__(self, *args, **kwargs):
            super(DepForm, self).__init__(*args, **kwargs)
            for field in self.fields.values():
                field.widget.attrs.update({'class': 'form-control'})
    
    
    
    
    
    def deplist(request):
        all_obj = models.Dep.objects.all()
        return render(request, 'deplist.html', {'msg': all_obj})
    
    
    def depedit(request, edit_id):
        obj = models.Dep.objects.filter(pk=edit_id).first()
        form_obj = DepForm(instance=obj)
        if request.method == 'POST':
            form_obj = DepForm(request.POST, instance=obj)
            if form_obj.is_valid():
                form_obj.save()
                return redirect(reverse('crm:deplist'))
        return render(request, 'depadd-edit.html', {'form_obj': form_obj})
    
    
    def depadd(request):
        form_obj = DepForm()
        if request.method == 'POST':
            form_obj = DepForm(request.POST)
            if form_obj.is_valid():
                form_obj.save()
                return redirect(reverse('crm:deplist'))
        return render(request, 'depadd-edit.html', {'form_obj': form_obj})
    
    
    def depdel(request, del_id):
        obj = models.Dep.objects.filter(pk=del_id).delete()
        return redirect(reverse('crm:deplist'))
    
    
    
    
    
    
    ###user-view
    
    from django.shortcuts import render, reverse, redirect, HttpResponse
    from crm import models
    from django import forms
    from django.forms import ValidationError
    import hashlib
    
    
    class UserFrom(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super(UserFrom, self).__init__(*args, **kwargs)
    
            for field in iter(self.fields):
                self.fields[field].widget.attrs.update({'class': 'form-control'})
    
        re_password = forms.CharField(
            label='确认密码',
            widget=forms.PasswordInput()
        )
    
        class Meta:
            model = models.User
            fields = ['name', 'age', 'sex', 'password', 're_password', 'dep', 'desc']
            widgets = {
                'password': forms.PasswordInput
            }
    
        sex = forms.ChoiceField(
            label='性别',
            choices=((0, ''), (1, '')),
            widget=forms.widgets.Select()
    
        )
    
        def clean(self):
            password = self.cleaned_data.get('password')
            re_password = self.cleaned_data.get('re_password')
            if password == re_password:
                md5 = hashlib.md5()
                md5.update(password.encode('utf-8'))
                self.cleaned_data['password'] = md5.hexdigest()
                return self.cleaned_data
            self.add_error('re_password', '两次密码不同!')
            raise ValidationError('两次密码不同!')
    
    
    def userlist(request):
        all_obj = models.User.objects.all()
        return render(request, 'userlist.html', {'msg': all_obj})
    
    
    def useredit(request, edit_id):
        obj = models.User.objects.filter(pk=edit_id).first()
        form_obj = UserFrom(instance=obj)
        if request.method == 'POST':
            form_obj = UserFrom(request.POST, instance=obj)
            if form_obj.is_valid():
                form_obj.save()
                return redirect(reverse('crm:userlist'))
        return render(request, 'depadd-edit.html', {'form_obj': form_obj})
    
    
    def useradd(request):
        form_obj = UserFrom()
        if request.method == 'POST':
            form_obj = UserFrom(request.POST)
            if form_obj.is_valid():
                form_obj.save()
                return redirect(reverse('crm:userlist'))
        return render(request, 'depadd-edit.html', {'form_obj': form_obj})
    
    
    def userdel(request, del_id):
        models.User.objects.filter(pk=del_id).delete()
        return redirect(reverse('crm:userlist'))
    View Code

      html部分

    ###deplist.html
    
    {% extends 'layout.html' %}
    {% load static %}
    {% block js %}
        <script src="{% static '/js/sweetalter.js' %}"></script>
        <script>
    
            $('.b1').click(function () {
    
                swal({
                    title: "提示",
                    text: "删除后无法恢复",
                    icon: "warning",
                    buttons: true,
                    dangerMode: true,
                })
                    .then((willDelete) => {
                        let del_id = $(this).attr('del_id');
                        if (willDelete) {
                            $.ajax({
                                url: '/crm/dep/del/'+del_id,
                                type: 'get',
                                success: () => {
                                    swal("已删除!", {
                                        icon: 'success',
                                    });
                                    $(this).parent().parent().remove()
                                }
                            });
                        } else {
                            swal("取消删除!");
                        }
                    });
            })
        </script>
    {% endblock %}
    {% block content %}
        <table class="text-center table table-striped table-bordered" style="margin-top: 20px">
            <tr>
                <td>序号</td>
                <td>id</td>
                <td>部门</td>
                <td>描述</td>
                <td>操作</td>
            </tr>
            {% for obj in msg %}
                <tr>
                    <td>{{ forloop.counter }}</td>
                    <td>{{ obj.pk }}</td>
                    <td>{{ obj.name }}</td>
                    <td>{{ obj.desc }}</td>
                    <td><a href={% url 'crm:depedit' obj.pk %}><i class="fa fa-pencil-square-o" aria-hidden="true">&nbsp&nbsp&nbsp</i></a>
                        <a class="b1" del_id="{{ obj.pk }}" style="color: red"><i class=" fa fa-remove" aria-hidden="true"></i></a></td>
                </tr>
            {% endfor %}
        </table>
    {% endblock %}
    
    
    ###userlist.html
    {% extends 'layout.html' %}
    {% load static %}
    {% block js %}
        <script src="{% static '/js/sweetalter.js' %}"></script>
        <script>
    
            $('.b1').click(function () {
    
                swal({
                    title: "提示",
                    text: "删除后无法恢复",
                    icon: "warning",
                    buttons: true,
                    dangerMode: true,
                })
                    .then((willDelete) => {
                        let del_url = $(this).attr('del_url');
                        if (willDelete) {
                            $.ajax({
                                url: del_url,
                                type: 'get',
                                success: () => {
                                    swal("已删除!", {
                                        icon: 'success',
                                    });
                                    $(this).parent().parent().remove()
                                }
                            });
                        } else {
                            swal("取消删除!");
                        }
                    });
            })
        </script>
    {% endblock %}
    {% block content %}
        <table class="text-center table table-striped table-bordered" style="margin-top: 20px">
            <tr>
                <td>序号</td>
                <td>id</td>
                <td>姓名</td>
                <td>年龄</td>
    {#            <td>密码</td>#}
                <td>部门</td>
                <td>描述</td>
                <td>操作</td>
            </tr>
            {% for obj in msg %}
                <tr>
                    <td>{{ forloop.counter }}</td>
                    <td>{{ obj.pk }}</td>
                    <td>{{ obj.name }}</td>
                    <td>{{ obj.age }}</td>
                    <td>{{ obj.dep }}</td>
                    <td>{{ obj.desc }}</td>
                    {% if obj.age %}
                        <td><a href={% url 'crm:useredit' obj.pk %}><i class="fa fa-pencil-square-o" aria-hidden="true">&nbsp&nbsp&nbsp</i></a>
                            <a class="b1" del_url="{% url 'crm:userdel' obj.pk %}" style="color: red"><i
                                    class=" fa fa-remove" aria-hidden="true"></i></a></td>
                    {% else %}
                        <td><a href={% url 'crm:depedit' obj.pk %}><i class="fa fa-pencil-square-o" aria-hidden="true">&nbsp&nbsp&nbsp</i></a>
                            <a class="b1" del_url="{% url 'crm:depdel' obj.pk %}" style="color: red"><i
                                    class=" fa fa-remove" aria-hidden="true"></i></a>
                        </td>
                    {% endif %}
                </tr>
            {% endfor %}
        </table>
    {% endblock %}
    
    
    
    ###edit-add.html
    {% extends 'layout.html' %}
    {% block content %}
        <div class="container col-lg-4 col-md-offset-3" style="margin-top: 30px;">
            <form class="form-horizontal" method="post" novalidate>
                {% csrf_token %}
                {% for obj in form_obj %}
                    <div class="form-group  {% if obj.errors %}has-error{% endif %}">
                        <label for="{{ obj.id_for_label }}"
                               class="col-sm-2 control-label">{{ obj.label }}</label>
                        <div class="col-sm-10">
                            {{ obj }}
                            <span class="help-block has-error">{{ obj.errors.0 }}</span>
                        </div>
                    </div>
                {% endfor %}
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" class="btn btn-default">保存</button>
                </div>
            </form>
        </div>
    {% endblock %}
    View Code
  • 相关阅读:
    python3.6中 字典类型和字符串类型互相转换的方法
    "sorted()"中的"Key Functions"
    tuple unpacking
    理解"__repr__"
    Python中的"Special Method"
    abstractmethod
    JavaScript括号中什么什么不加引号什么时候加引号?
    加载网页时速度慢的一些知识点
    Login登录页面的制作流程(摘要)
    JavaScript总结1
  • 原文地址:https://www.cnblogs.com/quguanwen/p/11438899.html
Copyright © 2011-2022 走看看