def get_detail(self, request, pk): try: res = self.model_class.objects.get(id=pk) except self.model_class.DoesNotExist: return JsonResponse(u'请选择合适的资源', status=0) ser = self.get_serializer(res).data ser_dic = dict(ser) resource_picture = '/media/' + str(res.resource_picture) if res.category.first(): ser_dic[u'category'] = res.category.first().id ser_dic[u'resource_pictures'] = resource_picture if ser_dic['picList']: l_pic = [] for pic in ser_dic['picList']: # pic = 'http://139.199.9.72:8010' + str(pic) pic = 'http://127.0.0.1:8000' + str(pic) l_pic.append(pic) ser_dic['picList'] = l_pic # pic_d={} # ser_dic[u'picList'] = [] # for pic in res.pic: # pic_d[u'name']='1.jpg' # pic_d[u'url']=pic # ser_dic[u'picList'].append(pic_d) # ser_dic[u'resource_picture']=[{u'name':'',u'url':str(res.resource_picture)}] return JsonResponse('ok', status=1, data=ser_dic)
def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if not serializer.is_valid(): return JsonResponse(u'数据错误',JsonResponse.CODE_ERROR_DATA,data=serializer.errors) serializer.save(author=request.user) headers = self.get_success_headers(serializer.data) return JsonResponse(data=serializer.data, headers=headers)
def rate_res(self, request): ''' 资源评价 :param request: :return: ''' data = request.data picList = data.get('picList', []) rate_content = data.get('rate_content', None) rate = data.get('rate', None) res_id = data.get('res_id', None) print picList try: res = Resource.objects.get(id=res_id) except Resource.DoesNotExist: return JsonResponse('请选择合适的资源', status=0) if rate and rate_content: res.rate = str(rate) res.rate_content = rate_content if picList: res.picList = picList res.save() orders = res.order.all() for order in orders: order.process = 5 order.save() else: return JsonResponse('请填写合适的内容', status=0) return JsonResponse('ok', status=1)
def regist(self,request,community_id): ''' 注册 :param request: :param community: :return: ''' data = request.data passwd = data.get('password',None) id_card = data.get('id_card',None) email = data.get('email',None) username = data.get('username',None) q = Q(Q(username=username)|Q(id_card=id_card)|Q(email=email)) queryset = User.objects.filter(q) if queryset: return JsonResponse(data={'status':0,'msg':'您的账号被已注册'},status=0) try: user = User.objects.create(username=username,address = data.get('address',None),email=email,id_card=data.get('id_card',None)) except: return JsonResponse(data={'status':0,'msg':'注册失败'},status=0) user.set_password(passwd) user.save() down = send_email_tt.s(user) down.delay() community = get_obj(Community,community_id) community.members.add(user) return JsonResponse(data={'status':1,'msg':'注册成功'},status=1)
def comment(self, request, pk): user = request.user obj = get_obj(self.model_class,pk) serializer = CommentSerializer(data=request.data) if not serializer.is_valid(): return JsonResponse(u'数据格式错误', code=JsonResponse.CODE_ERROR_DATA, data=serializer.errors) comment = Comment.objects.create(author=user, content_object=obj, **serializer.validated_data) serializer = CommentSerializer(comment) return JsonResponse(u'ok', data=serializer.data,status=1)
def get_resource_category(self, request, pkc): category = get_obj(Category, pkc) if isinstance(category, Category): res = self.model_class.objects.filter(Q(category=category), Q(is_used=False)) ser = self.get_serializer(res, many=True).data return JsonResponse('ok', status=1, data=ser) else: return JsonResponse(status=0)
def create(self, request, *args, **kwargs): serializer_class = kwargs.pop('serializer_class', None) assert serializer_class or self.serializer_class, ( u'serializer_class cannot be none!') serializer = self.serializer_class(data=request.data) if not serializer_class \ else serializer_class(data=request.data) if not serializer.is_valid(): return JsonResponse(code=JsonResponse.CODE_ERROR_DATA, data=serializer.errors) serializer.save() return JsonResponse(msg=u'成功')
def get_username(self,request): user = request.user a = cache.get(str(user.username)) print a if user.is_anonymous(): return JsonResponse('error', status=0) name = request.user.real_name serializer = self.get_serializer(user).data focus = user.focus.all() res = ResourceSerializer(focus,many=True,context={'request': request}).data return JsonResponse(name,status=1,data=res)
def search_obj(self,request): ''' 按名字搜索,模糊匹配 :param request: 搜索条件 :return: 搜索结果 ''' search_content = request.data.get('s',None) if not search_content: return JsonResponse(msg='数据错误,缺少参数',code=502,status=0) instances = self.model_class.objects.filter(name__contains=search_content) serializer = self.get_serializer(instances,many=True,context={'request': request}) return JsonResponse(msg='ok',data=serializer.data,status=1)
def create(self, request, *args, **kwargs): user = request.user data = request.data serializer = CommunitySerializer(data=data) if not serializer.is_valid(): return JsonResponse(code=JsonResponse.CODE_ERROR_DATA, data=serializer.errors) serializer.save(manager=user) community = serializer.instance community.members.add(user) community.save() return JsonResponse(u'创建成功', status=1)
def create(self, request, *args, **kwargs): ''' 生成订单 :param request: :param args: :param kwargs: :return: ''' buyer = request.user data_list = request.data.get('data', None) if not data_list: return JsonResponse(u'请传入合适的参数', status=0) for i in data_list: print i['id'] if int(i['id']) not in buyer.cart: # return JsonResponse(u'参数错误',status=0) pass for data in data_list: master_id = data['master']['id'] community_id = data['community']['id'] resource_id = data['id'] num = random.randint(1000000, 9999999) serializer = self.serializer_class(data=data) try: res = Resource.objects.get(id=resource_id) except Resource.DoesNotExist: return JsonResponse('请选择合适的资源') if res.is_used: return JsonResponse('请选择合适的资源,资源正在被其他人使用') if not serializer.is_valid(): return JsonResponse(JsonResponse.CODE_ERROR_DATA, serializer.errors) serializer.save(buyer=buyer, master_id=master_id, community_id=community_id, resource_id=resource_id, order_number=num) try: buyer.cart.remove(int(resource_id)) except ValueError: # return JsonResponse(u'此资源还没有加入购物车',status=0) pass try: res = Resource.objects.get(id=resource_id) buyer.focus.remove(res) except ValueError: # return JsonResponse(u'此资源还没有加入购物车',status=0) pass buyer.save() res.is_used = True res.save() return JsonResponse('ok', status=1)
def search_order_num(self, request): ''' 按订单号搜索,模糊匹配 :param request: 搜索条件 :return: 搜索结果 ''' search_content = request.data.get('s', None) if not search_content: return JsonResponse(msg='数据错误,缺少参数', code=502, status=0) instances = self.model_class.objects( order_number__contains=search_content) serializer = self.get_serializer(instances, many=True) return JsonResponse(msg='ok', data=serializer.data, status=1)
def return_back(self, request): ''' 归还 :param request: :return: ''' order_id = request.data.get('order_id', None) order = get_obj(self.model_class, order_id) if order.process in [1, 2]: return JsonResponse(u'资源没有在使用中,请检查', status=0) order.process = 4 order.save() return JsonResponse('ok', status=1)
def create(self, request, pk=None): ''' 创建资源 :param request: :param args: :param kwargs: :return: ''' import urllib data = request.data user = request.user # print data category_id = data.pop('category', []) resource_pictures = data.pop('resource_picture', []) print resource_pictures resource_pictures = urllib.unquote_plus(resource_pictures) print resource_pictures fname = str(resource_pictures).split('/')[-1] file_size = os.path.getsize(settings.MEDIA_ROOT + resource_pictures.split('/media')[-1]) with open(settings.MEDIA_ROOT + resource_pictures.split('/media')[-1], 'r') as f: resource_picture = UploadedFile(f, name=fname, size=file_size) data['resource_picture'] = resource_picture if not pk: serializer = self.get_serializer(data=data) if not serializer.is_valid(): return JsonResponse(code=JsonResponse.CODE_ERROR_DATA, data=serializer.errors) else: try: res = self.model_class.objects.get(id=pk) except self.model_class.DoesNotExist: return JsonResponse(u'请选择合适的资源', status=0) resource_picture = data.get('resource_picture', None) if not resource_picture: data.pop('resource_picture') serializer = self.get_serializer(instance=res, data=data) if not serializer.is_valid(): return JsonResponse(code=JsonResponse.CODE_ERROR_DATA, data=serializer.errors) community = user.belong_to_community.first() print 'com', community serializer.save(master=user, community_id=community.id) resource = serializer.instance # resource.community=community category = get_obj(Category, category_id) resource.category.add(category) resource.save() return JsonResponse(u'成功', status=1)
def sign_up(self, request, pk=None): data = request.data # print(pk) guest = self.queryset.filter(id=pk) if guest: if guest[0].sign == 1: return JsonResponse(msg='Guest has signed') else: guest.update(sign=1) serializer = GuestSerializer(guest, many=True) return JsonResponse(msg='Guest sign success', data=serializer.data) else: return JsonResponse(msg='Guest id error, no guest of this id')
def comment_article(self, request, pk): """评论文章""" try: article = Article.objects.get(id=pk) except Article.DoesNotExist: raise Http404('Article doesnot exist') data = request.data text = data.get('text') if not text: return JsonResponse(msg=u'数据不能为空', code=JsonResponse.CODE_ERROR) user = request.user comment = Comment(content_object=article, text=text, author=user) comment.save() serializer = CommentSerializer(comment) return JsonResponse(msg=u'评论成功', data=serializer.data)
def cancel(self, request): ''' 取消 :param request: :return: ''' order_id = request.data.get('order_id', None) order = get_obj(self.model_class, order_id) if order.process != 1: return JsonResponse(u'资源在使用中获取已关闭,请检查', status=0) order.process = 2 order.resource.is_used = False order.resource.save() order.save() return JsonResponse('ok', status=1)
def delete(self, request, pk): try: comment = Comment.objects.filter(id=pk) except Comment.DoesNotExist: raise Http404(u'评论不存在') comment.delete() return JsonResponse(msg=u'删除成功')
def get_pub(self, request): ''' 获取用户收藏资源 :param request: :return: ''' pubs = self.model_class.objects.filter(master=request.user) ser = self.get_serializer(pubs, many=True).data ser_ls = list(ser) l = [] for pub in pubs: if pub.order.first(): l.append(pub.order.first().process) else: l.append(0) for i in range(len(ser_ls)): if l: ser_ls[i]['process'] = l[i] if ser_ls[i]['picList']: l_pic = [] for pic in ser_ls[i]['picList']: # pic = 'http://139.199.9.72:8010' + str(pic) pic = 'http://127.0.0.1:8000' + str(pic) l_pic.append(pic) ser_ls[i]['picList'] = l_pic return JsonResponse('ok', status=1, data=ser_ls)
def create_guest(self, request): data = request.data realname = data['realname'] phone = data['phone'] email = data['email'] event = data['eventid'] if realname and phone and email and event: guest = Guest.objects.create(realname=realname, phone=phone, email=email, event_id=event) serializer = GuestSerializer(guest) return JsonResponse(msg='Create guest success', data=serializer.data) else: return JsonResponse(msg='parameter wrong', code=404)
def user_login(self,request): ''' :param request: :return: ''' data = request.data username = data.get('username',None) passwd = data.get('password',None) user = auth.authenticate(username=username,password=passwd) if not user: return JsonResponse(data={'status':0,'msg':'颤抖吧,凡人,你的用户名或者密码错误,哈哈哈'},status=0) if user.status == 3: return JsonResponse(data={'status':0,'msg':'你已经被删除,say goodbye~~'},status=0) elif user.status == 1: return JsonResponse(data={'status': 0, 'msg': '你已经被冻结,不能登录,请联系管理员,尽快承认错误'},status=0) auth.login(request, user) cache.set(str(user.username), user.real_name, timeout=300) return JsonResponse(data={'status': 1, 'msg': '被选召的孩子,出发吧','username':user.username},status=1)
def get_collections(self, request): ''' 获取用户收藏资源 :param request: :return: ''' collections = request.user.focus.all() ser = self.get_serializer(collections, many=True).data return JsonResponse('ok', status=1, data=ser)
def get_user_info(self, request): obj = request.user serializer = self.serializer_class(obj, context={'request': request}).data community = request.user.belong_to_community.all() if community: serializer['region']=community[0].id else: serializer['region'] = "" return JsonResponse(data=serializer,status=1)
def get_district(self, request, city_id): ''' 获取县 :param request: :param city_id: 市id :return: ''' districts = District.objects.filter(city_id=city_id) serializer = DistrictSerializer(districts, many=True) return JsonResponse(data=serializer.data)
def get_city(self, request, province_id): ''' 获取市 :param request: :param province_id: 省id‘ :return: ''' citys = City.objects.filter(province_id=province_id) serializer = CitySerializer(citys, many=True) return JsonResponse(data=serializer.data)
def get_cart_list(self,request): ''' 获取购物车列表 :param request: :return: ''' car_list = request.user.cart resources = Resource.objects.filter(id__in = car_list) serializer = ResourceSerializer(resources,many=True,context={'request': request}) return JsonResponse('ok',data=serializer.data,status=1)
def get_paginated_response_status(self, request, queryset, serializer_class=None, context=None,status=None): page = self.paginate_queryset(queryset) serializer = self.get_serializer(page, many=True) if not serializer_class \ else serializer_class(page, context={'request':request}, many=True) other_dict = OrderedDict([ ('count', self.paginator.page.paginator.count), ('next', self.paginator.get_next_link()), ('previous', self.paginator.get_previous_link()), ]) return JsonResponse(data=serializer.data, other_dict=other_dict,status=status)
def createp(self, request): pic = request.data.get('file', None) filename = request.data.get('filename', None) try: resp = Respic.objects.create(pic=pic) except: return JsonResponse('faile', status=0) print 'media/' + str(resp.pic) data = {'name': filename, 'url': '/media/' + str(resp.pic)} return Response(data)
def change_name(self, request): data = request.data query_list = [] change_name = data.get("changeName", '') real_name = data.get("realname", '') event_id = data.get("event", '') if real_name and event_id: query_list.append(Q(realname=real_name)) query_list.append(Q(event=event_id)) change_guest = self.queryset.filter(*query_list) if change_guest: if change_guest[0].realname == change_name: return JsonResponse(msg='Change name same as real name', code=400) change_guest.update(realname=change_name) logger.info('get change name success') return JsonResponse(msg='Change name success', data=change_name) else: return JsonResponse(msg='Real name or event id wrong', code=400)
def sort_obj(self,request): ''' 按任意属性排序 :param request: 排序方式 获取排序方式 排序 :return:排序结果 ''' sort_way = request.data.get('sort_way',None) # print sort_way,dir(self.model_class) # print self.model_class.__dict__.keys() # print self.model_class._meta.fields fs = [f.name for f in self.model_class._meta.fields] if not sort_way: serializer = self.get_serializer(self.get_queryset(),many=True) return JsonResponse(msg='ok',data=serializer.data,status=1) if sort_way not in fs: return JsonResponse(msg='没有这个排序方式',code = 404,status=0) serializer = self.get_serializer(self.get_queryset().order_by('-'+sort_way),many=True) return JsonResponse(msg='ok', data=serializer.data, status=1)