更新内容:
将我的客户和公共客户写入一个视图函数
跟进记录表
forms.ModelChoiceField( queryset=models.Userinfo.objects.all( )
model中的外键字段,form在渲染的时候按照上面的代码渲染,从数据库中将选项读出来
可以设置筛选条件,显示特定的内容
from django.shortcuts import render,HttpResponse,redirect import os from django.contrib import auth from app01.models import UserInfo from crm import settings from django.views import View from django import forms from app01 import models from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required # Create your views here. class RegForm(forms.Form): username = forms.CharField( label='用户名', max_length=12, min_length=6, error_messages={ 'max_length':'用户名不能超过12位', 'min_length':'用户名不能低于6位', 'required':'用户名不能为空', } ) password = forms.CharField( label='密码', max_length=16, min_length=6, error_messages={ 'max_length': '密码不能超过12位', 'min_length': '密码不能低于6位', 'required': '密码不能为空', }, widget=forms.widgets.PasswordInput(render_value=True), ) r_password = forms.CharField( label='密码', max_length=16, min_length=6, error_messages={ 'max_length': '密码不能超过12位', 'min_length': '密码不能低于6位', 'required': '密码不能为空', }, widget=forms.widgets.PasswordInput, ) def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) for field in self.fields: self.fields[field].widget.attrs.update({'class':'form-control'}) def get_valid_img(request): from PIL import Image #终极版,方式5 import random def get_random_color(): return (random.randint(0,255),random.randint(0,255),random.randint(0,255)) from PIL import Image,ImageDraw,ImageFont img_obj = Image.new('RGB', (236, 34), get_random_color()) #图片对象 draw_obj = ImageDraw.Draw(img_obj) #通过图片对象生成一个画笔对象 font_path = os.path.join(settings.BASE_DIR,'statics/font/ziti.TTF') #获取字体,注意有些字体文件不能识别数字,所以如果数字显示不出来,就换个字体 font_obj = ImageFont.truetype(font_path,16) #创建字体对象 sum_str = '' #这个数据就是用户需要输入的验证码的内容 for i in range(6): a = random.choice([str(random.randint(0,9)), chr(random.randint(97,122)), chr(random.randint(65,90))]) #4 a 5 D 6 S sum_str += a # print(sum_str) draw_obj.text((84,10),sum_str,fill=get_random_color(),font=font_obj) #通过画笔对象,添加文字 width=236 height=34 # 添加噪线 for i in range(5): #添加了5条线 #一个坐标表示一个点,两个点就可以连成一条线 x1=random.randint(0,width) x2=random.randint(0,width) y1=random.randint(0,height) y2=random.randint(0,height) draw_obj.line((x1,y1,x2,y2),fill=get_random_color()) # # 添加噪点 for i in range(10): #这是添加点,50个点 draw_obj.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color()) #下面是添加很小的弧线,看上去类似于一个点,50个小弧线 x = random.randint(0, width) y = random.randint(0, height) draw_obj.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color()) #x, y是弧线的起始点位置,x + 4, y + 4是弧线的结束点位置 from io import BytesIO f = BytesIO() #操作内存的把手 img_obj.save(f,'png') # data = f.getvalue() # 存这个验证码的方式1:赋值给全局变量的简单测试 # global valid_str # valid_str = sum_str # 方式2:将验证码存在各用户自己的session中,session的应用其实还有很多 print(sum_str) request.session['valid_str'] = sum_str return HttpResponse(data) class Login(View): def get(self,request): return render(request,'login.html') def post(self,request): data = request.POST if data.get('code') == request.session['valid_str']: user_obj = auth.authenticate(username=data.get('username'),password=data.get('password')) if user_obj: auth.login(request,user_obj) return redirect('customers') else: print('用户名或者密码错误') return redirect('login') else: return render(request,'login.html') class Register(View): def get(self, request): form_obj = RegForm() return render(request, 'register.html',{"form_obj":form_obj}) def post(self,request): data = request.POST form_obj = RegForm(data) code = data.get('code') error = '' if code == request.session['valid_str']: if data.get('password') == data.get('r_password'): if form_obj.is_valid(): user_obj = UserInfo.objects.create_user(username=data.get('username'),password=data.get('password')) return redirect('login') else: erro = '两次密码不一致' else: erro = '验证码错误' return render(request, 'register.html',{"form_obj":form_obj,'error':erro}) # from app01.page import PageNation # class Index(View): # @method_decorator(login_required()) # def dispatch(self, request, *args, **kwargs): # ret = super(Index, self).dispatch(request,*args,**kwargs) # return ret # # def get(self,request): # # all_costomer = models.Customer.objects.all() # #self,base_url,current_page_num,total_counts,per_page_counts=10,page_number=5 # costomer_obj = PageNation(request.path,request.GET.get('page'),all_costomer.count()) # start_num = costomer_obj.start_num # end_num = costomer_obj.end_num # page_html = costomer_obj.page_html() # # print(page_html) # costomers = all_costomer[start_num:end_num] # return render(request,'index.html',{'all_costomer':costomers,'page_html':page_html}) # # def post(self,request): # condition = request.POST.get('condition') # wd = request.POST.get('wd') # print('condition:wd',condition,wd) # from django.db.models import Q # q = Q() # q.children.append((condition,wd)) # print('q',q) # @login_required() # def index(request): # return render(request,'index.html') class Logout(View): def get(self,request): auth.logout(request) return redirect('login') class Start(View): def get(self,request): return render(request,'starter.html') from app01 import myform class Addcostomer(View): def get(self,request): customerform = myform.CustomerForm() return render(request,'addcustomer.html',{'customerform':customerform}) def post(self,request): data = request.POST customerform = myform.CustomerForm(data) if customerform.is_valid(): customerform.save() return redirect('customers') else: return render(request,'addcustomer.html',{'customerform':customerform}) class Edicustomer(View): def get(self,request,pk): # print(pk) customer_obj = models.Customer.objects.get(pk=pk) customer_form = myform.CustomerForm(instance=customer_obj) return render(request,'edicustomer.html',{'customerform':customer_form}) def post(self,request,pk): customer_obj = models.Customer.objects.get(pk=pk) customer_form = myform.CustomerForm(request.POST,instance=customer_obj) if customer_form.is_valid(): customer_obj.save() return redirect('index') else: return render(request,'edicustomer.html', {'customerform':customer_form}) class Delcustomer(View): def get(self,request,pk): # print(pk) models.Customer.objects.filter(pk=pk).delete() return redirect('index') class FilterCustomer(View): def get(self,request): pass # return render(request,'filtercustomer.html',{'all_customer':all_customer}) from django.urls import reverse from app01 import page2 #老师讲的 ,带分页效果的客户信息展示 # 将我的客户 和公共客户通过一个视图函数和html实现 class Customers(View): def get(self,request): wd = request.GET.get('wd','') condition = request.GET.get('condition','') # print(request.path) # print(reversed('customers')) if request.path == reverse('customers'): #筛选公共用户 flag = 1 all_customers = models.Customer.objects.filter(consultant__isnull=True) else: flag = 0 all_customers = models.Customer.objects.filter(consultant=request.user) from django.db.models import Q if wd: #如果有筛选条件 q = Q() q.children.append((condition,wd)) #将公共用户根据筛选条件再次进行筛选 all_customers = all_customers.filter(q) per_page_counts = 5 page_number = 11 total_count = all_customers.count() current_page_num = request.GET.get('page',1) #通过分页类实例化一个 分页对象 page_obj = page2.PageNation(request.path, current_page_num, total_count, request,per_page_counts,page_number) all_customers = all_customers.order_by('-pk')[page_obj.start_num:page_obj.end_num] # all_customers = all_customers.order_by('-pk')[page_obj.start_num, page_obj.end_num] ret_html = page_obj.page_html() return render(request,'customers.html', {'all_customers':all_customers,'ret_html':ret_html,'flag':flag}) def post(self,request): self.data = request.POST.getlist('selected_id') print(self.data) action = request.POST.get('action') if hasattr(self,action): func = getattr(self,action) if callable(func): func(request) return redirect(request.path) else: return HttpResponse('别动') else: return HttpResponse('不要搞事情') def batch_delete(self,request): models.Customer.objects.filter(pk__in=self.data).delete() def batch_update(self,request): models.Customer.objects.filter(pk__in=self.data).update(name='熊哥') def batch_reverse_gs(self,request): models.Customer.objects.filter(pk__in=self.data).update(consultant=request.user) def batch_reverse_sg(self,request): models.Customer.objects.filter(pk__in=self.data).update(consultant=None) # class Mycustomers(View): # # def get(self,request): # wd = request.GET.get('wd','') # condition = request.GET.get('condition','') # # #筛选公共用户 # all_customers = models.Customer.objects.filter(consultant__username=request.user) # print(all_customers) # # from django.db.models import Q # if wd: #如果有筛选条件 # q = Q() # q.children.append((condition,wd)) # # #将公共用户根据筛选条件再次进行筛选 # all_customers = all_customers.filter(q) # # per_page_counts = 5 # page_number = 11 # total_count = all_customers.count() # current_page_num = request.GET.get('page',1) # # #通过分页类实例化一个 分页对象 # page_obj = page2.PageNation(request.path, current_page_num, total_count, request,per_page_counts,page_number) # # all_customers = all_customers.order_by('-pk')[page_obj.start_num:page_obj.end_num] # # all_customers = all_customers.order_by('-pk')[page_obj.start_num, page_obj.end_num] # # ret_html = page_obj.page_html() # # return render(request,'customers.html', {'all_customers':all_customers,'ret_html':ret_html}) from django.db.models import Q from app01.myform import ConsultrecordForm class Myrecords(View): def get(self,request,pk=None): # consultrecordform = ConsultrecordForm() action = request.GET.get('action') wd = request.GET.get('wd') q = Q() q.children.append((action,wd)) if wd: print(wd) print(q) all_record = models.ConsultRecord.objects.filter(q) else: all_record = models.ConsultRecord.objects.all() if pk: record_obj = models.ConsultRecord.objects.filter(pk=pk).first() all_records = all_record.filter(customer=record_obj.customer) else: all_records = all_record.order_by('-pk') per_page_counts = 5 page_number = 5 total_counts = all_records.count() base_url = request.path current_page_number = request.GET.get('page',1) page_obj = page2.PageNation(base_url,current_page_number,total_counts,request,per_page_counts,page_number) all_records = all_records[page_obj.start_num:page_obj.end_num] page_html = page_obj.page_html() return render(request,'consultrecord.html',{'all_records':all_records,'page_html':page_html}) class Addrecords(View): def get(self,request): addrecordform = myform.ConsultrecordForm(request) return render(request,'addrecords.html',{'addrecordform':addrecordform}) def post(self,request): data = request.POST addrecordform = myform.ConsultrecordForm(request,data) if addrecordform.is_valid(): addrecordform.save() return redirect('myrecords') else: return redirect('addrecords') #将删除和编辑写在一个视图函数,利用request.path 中是否有edi字样来判断执行哪个操作 class Optrecord(View): def get(self,request,pk): if 'edi' in request.path: print(1) self.record_obj = models.ConsultRecord.objects.filter(pk=pk).first() record_form = myform.ConsultrecordForm(request,instance=self.record_obj) return render(request,'editrecords.html',{'record_form':record_form}) else: models.ConsultRecord.objects.filter(pk=pk).delete() return redirect('myrecords') def post(self,request,pk): data = request.POST self.record_obj = models.ConsultRecord.objects.filter(pk=pk).first() record_form = myform.ConsultrecordForm(request,data,instance=self.record_obj) if record_form.is_valid(): record_form.save() return redirect('myrecords') else: return render(request,'editrecords.html',{'record_form':data})
html
{% extends 'starter.html' %} {% block content %} <div class="content-wrapper"> <section class="content-header"> <h1> 跟进信息展示 <small>展示</small> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> Level</a></li> <li class="active">Here</li> </ol> </section> <section class="content catainer-fluid"> <div class="row"> <div class="col-xs-12"> <div class="box"> <a href="{% url 'addrecords' %}" class="btn btn-primary pull-right">添加记录</a> <div class="pull-right" style="border: 1px solid blue;"> <form action=""> <select name="action" id=""> <option value="customer__name" class="form-control " style="display: inline-block">客户名</option> <input type="text" name="wd" class="form-control" style="width:40px ;display: inline-block"> <input type="submit" class="btn btn-primary" value="go"> </select> </form> </div> <form action="" method="post"> <select name="action" id="" class="form-control" style="width: 100px;display: inline-block;"> <option name="batch-delete" value="">批量删除</option> <option name="batch-update" value="">批量修改</option> </select> <input type="submit" class="btn btn-primary" value="go" style="vertical-align: 1px; horiz-align: left"> <table class="table table-bordered"> <thead> <tr> <th> <input type="checkbox" id="choose"> </th> <th>序号</th> <th>跟进客户</th> <th>跟进内容</th> <th>跟进状态</th> <th>跟进日期</th> <th>跟进人</th> <th>操作</th> </tr> </thead> <tbody> {% for record in all_records %} <tr> <td> <input type="checkbox" name="selected_id" value="{{ record.pk }}"> </td> <td>{{ forloop.counter }}</td> <td>{{ record.customer }}</td> <td>{{ record.note }}</td> <td>{{ record.get_status_display }}</td> <td>{{ record.date|date:'Y-m-d' }}</td> <td>{{ record.consultant }}</td> <td> <a href="{% url 'editrecord' record.pk %}" class="btn btn-warning">修改</a> <a href="{% url 'delrecord' record.pk %}" class="btn btn-danger">删除</a> <a href="{% url 'selfrecords' record.pk %}" class="btn btn-primary">详细信息</a> </td> </tr> {% endfor %} </tbody> </table> {{ page_html|safe }} </form> </div> </div> </div> </section> </div>> {% endblock %} {% block js %} <script> $('#choose').click(function () { var status = $(this).prop('checked'); $('[name=selected_id]').prop('checked',status) }) </script> {% endblock %}
myform.py
from django import forms from app01 import models class CustomerForm(forms.ModelForm): class Meta: model = models.Customer fields = '__all__' labels = { 'qq':'qq号', 'name':'姓名', } widgets = { 'course':forms.widgets.SelectMultiple() } def __init__(self,*args,**kwargs): super(CustomerForm, self).__init__(*args,**kwargs) for field in self.fields: print(field,type(field)) # if field == 'course': # print('lalalalalal') # # elif field == 'birthday': # # pass # self.fields[field].widget = forms.widgets.DateInput({'type':'date','class':'form-control'}) # else: self.fields[field].widget.attrs.update({'class': 'form-control'}) class ConsultrecordForm(forms.ModelForm): class Meta: model = models.ConsultRecord fields = '__all__' labels = { 'note':'记录', } exclude = ['delete_status',] def __init__(self,request,*args,**kwargs): super(ConsultrecordForm, self).__init__(*args,**kwargs) self.fields['consultant'].queryset = models.UserInfo.objects.filter(pk=request.user.pk) self.fields['customer'].queryset = models.Customer.objects.filter(consultant=request.user) for field in self.fields: self.fields[field].widget.attrs.update({'class':'form-control'})