def poll_create(request): if request.user.is_authenticated(): if request.method == 'POST': poll_form = PollCreateForm(request.POST, prefix="poll") if poll_form.is_valid(): print 'Valid Form' unsaved_poll = poll_form.save(commit=False) unsaved_poll.member = request.user.members unsaved_poll.save() history = History(user = request.user.members, item_type = 'POLL', item_id = unsaved_poll.id) history.save() return HttpResponseRedirect("/polls/"+str(unsaved_poll.id)) poll_form = PollCreateForm(prefix="poll") try: polls = Poll.objects.filter(member = request.user.members) except: polls = [] template_dict = { 'error': '', 'poll_form' : poll_form, 'polls': polls } return render_to_response( 'user_pages/polls/poll_create.html', template_dict, context_instance=RequestContext(request) ) else: return HttpResponseRedirect("/login/")
def recover(self, request): ''' Allows users to ask for password recovery(which needs to be confirmed). ''' if request.user.is_authenticated(): return Response({ 'error': "An already logged in user can't recover a password!" }) email = request.data.get('email', None) if email != None: email = email.lower() try: usr = User.objects.get(email=email) ur = UserRecovery(user=usr) ur.save() History.new(event=History.RECOVER, actor=usr, object=ur, authorized=[usr]) return Response({'success': True}) except User.DoesNotExist: pass return Response( {'error': "An user with this email does not exist."})
def changePassword(self, request): ''' Allows users to change their own password, after confirming a password recovery. ''' if request.user.is_authenticated(): return Response( { 'error': "An already logged in user can't recover a password!" }, status=status.HTTP_400_BAD_REQUEST) hash = request.data.get('hash', None) new_password = request.data.get('password', None) if hash != None and new_password != None: try: userRecovery = UserRecovery.getUserRecovery(hash=hash) userRecovery.setNewPassword(new_password) History.new(event=History.EDIT, actor=userRecovery.user, object=userRecovery.user, authorized=[userRecovery.user]) return Response({'success': True}, status=status.HTTP_200_OK) except (UserRecovery.DoesNotExist, AttributeError): return Response({ 'error': "Either the request does not exist, or it has expired." }) return Response({'error': "This request is not valid."})
def retrieve(self, request, *args, **kwargs): """ Retrieve a task details, by id """ History.new(event=History.ACCESS, actor=request.user, object=self.get_object()) return super(TaskViewSet, self).retrieve(request, args, kwargs)
def create(self, request, *args, **kwargs): """ Insert a new workflow """ request.data[u'owner'] = request.user.id d = copy.deepcopy(request.data) request.data.pop('tasks') # first round without tasks, to get reference to workflow instance serializer, headers = create_serializer(self, request) # create tasks... wf = serializer.save() d = self.__linkTasks(d, wf) print d serializer = WorkflowSerializer(instance=wf, data=d, partial=True) serializer.is_valid(raise_exception=True) # add tasks dependencies serializer.save() History.new(event=History.ADD, actor=request.user, object=serializer.instance) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def invite(self, request): ''' Allows a user to register anothers users. Being then put on a waiting list to be approved. ''' userList = [] for usr in request.data: email = usr.get('email', None) password = "******" #Default password, the user will be notice to change it. This needs to be changed if email != None: email = email.lower() try: usr = User.objects.get(email=email) userList += [usr] except User.DoesNotExist: try: usr['first_name'] = usr['firstName'] usr['last_name'] = usr['lastName'] except: usr['first_name'] = "" usr['last_name'] = "" usr['username'] = email[:30] usr['email'] = email usr['profile'] = { 'detail_mode': Profile.get_default_detail_mode() } serializer = UserSerializer(data=usr) valid = serializer.is_valid(raise_exception=True) if valid: new_user = serializer.save() new_user.set_password(password) new_user.is_active = True #I decide let the userbe active in the first place because this is a invite new_user.save() userList += [new_user] ur = UserRecovery(user=new_user) ur.save() History.new(event=History.INVITE, actor=request.user, object=ur, authorized=[new_user]) else: return Response({ 'error': "Email are mandatory fields on registering a new user" }) serializer_context = { 'request': request, } serializerAll = UserSerializer(userList, many=True, context=serializer_context) return Response(serializerAll.data)
def register(self, request): ''' Allows users to register themselves. Being then put on a waiting list to be approved. ''' if request.user.is_authenticated(): return Response( { 'error': "An already registered user can't register new users!" }, status.HTTP_400_BAD_REQUEST) dataRequest = request.data.copy() password = dataRequest.pop('password', None) email = dataRequest.get('email', None) if email != None and password != None: email = email.lower() try: user = User.objects.get(email=email) return Response( {'error': "An user with this email already exists"}, status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: if (not 'username' in dataRequest): dataRequest['username'] = email[:30] dataRequest['email'] = email serializer = UserSerializer(data=dataRequest, context={'request': request}) user_validated = serializer.is_valid(raise_exception=True) if user_validated: new_user = serializer.save() new_user.set_password(password) new_user.is_active = False new_user.save() staff = User.objects.filter(is_staff=True) History.new(event=History.ADD, actor=new_user, object=new_user, authorized=staff) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response({'error': "User details invalid"}, status=status.HTTP_400_BAD_REQUEST) return Response( { 'error': "Email and password are mandatory fields on registering a new user" }, status=status.HTTP_400_BAD_REQUEST)
def retrieve(self, request, *args, **kwargs): """ Retrieve a resource details, by hash """ History.new(event=History.ACCESS, actor=request.user, object=self.get_object()) return super(ResourceViewSet, self).retrieve(request, args, kwargs)
def defeat(self, event): profile = Profile.objects.get(user_id=event['data']['player']) profile.defeat = profile.defeat + 1 profile.save() history = History(user_id=event['data']['player'], text="Lose a fight", type="defeat") history.save()
def retrieve(self, request, *args, **kwargs): """ Retrieve a result, by id """ instance = self.get_object() History.new(event=History.ACCESS, actor=request.user, object=instance, related=[instance.processtaskuser.processtask.process]) return super(ResultViewSet, self).retrieve(request, args, kwargs)
def victory(self, event): profile = Profile.objects.get(user_id=event['data']['player']) profile.victory = profile.victory + 1 profile.save() history = History(user_id=event['data']['player'], text="Won a fight", type="victory") history.save()
def retrieve(self, request, *args, **kwargs): """ Retrieve a form, by id """ instance = self.get_object() History.new(event=History.ACCESS, actor=request.user, object=instance) return Response(FormSerializer(instance).data)
def reject(self, comment): self.status = ProcessTaskUser.REJECTED self.save() History.new(event=History.REJECT, actor=self.user, object=self, observations=comment) self.processtask.refreshState() self.processtask.move()
def create(self, request, *args, **kwargs): """ Add a result as a response to a task """ serializer, headers = create_serializer(self, request) History.new(event=History.ADD, actor=request.user, object=serializer.instance) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def retrieve(self, request, *args, **kwargs): """ Retrieve a workflow, by id including related tasks """ History.new(event=History.ACCESS, actor=request.user, object=self.get_object()) return Response(WorkflowDetailSerializer(self.get_object()).data)
def res(request): f = Cart.objects.filter(customer=request.user) print(f) for i in range(0, len(f)): h = History() h.item = f[i].name h.quantity = f[i].quantity h.totalcost = f[i].totalcost h.customer = f[i].customer h.order_date = timezone.datetime.now() #h.reserve_time = s print(f[i]) f[i].delete() h.save() print(h) t = Transactions() t.customer = request.user t.totalcost = (request.POST['cost']) t.order_date = timezone.datetime.now() t.save() #------------------------------------send mail---------------------------------------------- hi = History.objects.filter(customer=request.user, status="P") rec = str(request.user.email) html_content = render_to_string('transaction/email.html', {'hi': hi}) text_content = strip_tags(html_content) email = EmailMultiAlternatives("Your Order", text_content, settings.EMAIL_HOST_USER, [rec]) email.attach_alternative(html_content, "text/html") email.send() return redirect('home')
def create_trip(request, traveller_id): traveller_user = get_object_or_404(Traveller, pk=traveller_id) traveller_user_logged_in = get_object_or_404(Traveller, email=request.user) guide_user = get_object_or_404(Guide, email=request.user) if 'confirm' in request.POST: traveller = traveller_user.email guide = request.user place = Place.objects.filter(name=request.POST['place']).first() no_of_people = request.POST['no_of_people'] no_of_children = request.POST['no_of_children'] total_hours = request.POST['travel_hours'] nop = float(no_of_people) noc = float(no_of_children) noh = float(total_hours) if ((nop + noc * 0.75) <= 2): tp = 2 * noh * float(guide_user.price) tp = int(tp) elif ((nop + noc * 0.75) >= 8): tp = 8 * noh * float(guide_user.price) tp = int(tp) else: tp = (nop + noc * 0.75) * noh * float(guide_user.price) tp = int(tp) history = History(traveller=traveller, guide=guide, place=place, no_of_people=no_of_people, no_of_children=no_of_children, total_hours=total_hours, total_price=tp) history.save() trip_notification = Trip_Notification( receiver_email=traveller_user.email, sender_email=request.user, form=history) trip_notification.save() traveller_id = request.POST['traveller_id'] return redirect('/view_profile/' + traveller_id) places = guide_user.places.all() place_pattern = '' for place in places: place_pattern = place.name + '|' + place_pattern context = { 'traveller_user': traveller_user, 'logged_in_user': traveller_user_logged_in, 'places': places, 'place_pattern': place_pattern[:-1], 'guide_user': guide_user, } # print(guide_user.place) return render(request, 'travellers/create_trip.html', context)
def destroy(self, request, *args, **kwargs): """ Delete a form, by id """ instance = self.get_object() instance.removed = True instance.save() History.new(event=History.DELETE, actor=request.user, object=instance) return Response(status=status.HTTP_204_NO_CONTENT)
def signed(request, pet_id): p = get_object_or_404(Petition, pk=pet_id) userobject = get_object_or_404(Member, user=request.user) print userobject print "^^userobject^^" already_signed = SignPetition.objects.filter(user=userobject).filter( signedpet_id=pet_id) print already_signed if request.method == 'POST': signform = PetitionSignForm(request.POST) if already_signed: print "user already signed this petition!!!" elif signform.is_valid(): print 'user not signed yet. going to update database' instance = signform.save(commit=False) instance.user = userobject instance.signedpet = p instance.save() p.current_num = p.current_num + 1 p.save() new_hist = History() new_hist.user = userobject new_hist.item_type = "SIGN" new_hist.timestamp = datetime.datetime.now() new_hist.item_id = instance.id new_hist.save() return HttpResponseRedirect('/petitions/' + pet_id + '/')
def index(request): userobject = Member.objects.get(user=request.user) print userobject if request.method == 'POST': form = PetitionForm(request.POST) if form.is_valid(): newpetobj = form.save(commit=False) newpetobj.user = userobject newpetobj.current_num = 0 newpetobj.timestamp = datetime.datetime.now() newpetobj.save() new_hist = History() new_hist.user = userobject new_hist.item_type = "PETITION" new_hist.timestamp = newpetobj.timestamp new_hist.item_id = newpetobj.id new_hist.save() return HttpResponseRedirect('/petitions/') else: form = PetitionForm() return render_to_response('user_pages/home/base_home_petitions.html', { 'form': form, }, context_instance=RequestContext(request))
def index(request): userobject = Member.objects.get(user=request.user) inv_list = Invited.objects.filter(invited_user=userobject).values_list( 'debateinvite_id', flat=True) debate_list = Debate.objects.filter(id__in=inv_list) part_list = Participants.objects.filter( participant=userobject).values_list('debateparticipate_id', flat=True) part_deb_list = Debate.objects.filter(id__in=part_list) if request.method == 'POST': #form1=InviteDebateForm() form2 = ParticipantDebateForm() form = CreateDebateForm(request.POST) print 'request method is post(index)' if form.is_valid(): print 'form is valid(index)' new_debate = form.save(commit=False) new_debate.created_by = userobject new_debate.privacy = "none" new_debate.timestamp = datetime.datetime.now() new_debate.save() # # HISTORY TABLE UPDATION>>> # new_hist = History() new_hist.user = userobject new_hist.item_type = "DEBATE" new_hist.timestamp = new_debate.timestamp new_hist.item_id = new_debate.id new_hist.save() #p=get_object_or_404(Debate,pk=pet_id) print new_debate.num_part formset1 = formset_factory(InviteDebateForm, extra=new_debate.num_part) form1 = formset1() return render_to_response('user_pages/home/base_home_debate.html', { 'dform1': form1, 'dform2': form2, 'new_debate': new_debate, 'cur_user': request.user }, context_instance=RequestContext(request)) else: form = CreateDebateForm() return render_to_response('user_pages/home/base_home_debate.html', { 'debate_list': debate_list, 'part_deb_list': part_deb_list, 'dform': form, }, context_instance=RequestContext(request)) else: form = CreateDebateForm() return render_to_response('user_pages/home/base_home_debate.html', { 'debate_list': debate_list, 'part_deb_list': part_deb_list, 'dform': form, }, context_instance=RequestContext(request))
def update(self, request, *args, **kwargs): """ Update a task """ partial = kwargs.pop('partial', False) instance = self.get_object() serializer = instance.init_serializer(instance=instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) History.new(event=History.EDIT, actor=request.user, object=instance) return Response(serializer.data)
def fork(self, request, hash=None): """ Duplicates a public or owned workflow, returning the duplicate """ workflow = self.get_object() if workflow.permissions().forkable: new_workflow = workflow.fork(owner=request.user) History.new(event=History.ADD, actor=request.user, object=new_workflow) return Response(WorkflowSerializer(new_workflow).data) return Response({"error": "Workflow isn't forkable"}, 403)
def create(self, request, *args, **kwargs): """ Insert a new Form """ request.data[u'creator'] = request.user.id serializer, headers = create_serializer(self, request) History.new(event=History.ADD, actor=request.user, object=serializer.instance) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def register(self, request): ''' Allows users to register themselves. Being then put on a waiting list to be approved. ''' if request.user.is_authenticated(): return Response({ 'error': "An already registered user can't register new users!" }) password = request.data.pop('password', None) email = request.data.get('email', None) if email != None and password != None: email = email.lower() try: usr = User.objects.get(email=email) return Response( {'error': "An user with this email already exists"}) except User.DoesNotExist: request.data['username'] = email[:30] request.data['email'] = email serializer = UserSerializer(data=request.data, context={'request': request}) valid = serializer.is_valid(raise_exception=True) if valid: new_user = serializer.save() new_user.set_password(password) new_user.is_active = False new_user.save() History.new(event=History.ADD, actor=new_user, object=new_user, authorized=User.objects.filter(is_staff=True)) return Response(serializer.data) return Response({'error': "User details invalid"}) return Response({ 'error': "Email and password are mandatory fields on registering a new user" })
def warnBeforeDeadlines(): allProcess = Process.allWithNotificationBeforeDelay() for process in allProcess: ptasks = ProcessTask.all(process=process).filter( status=ProcessTask.RUNNING) for ptask in ptasks: if (((ptask.deadline - timezone.now()).days + 1) == process.days_before_delay): pusers = ptask.users() for puser in pusers: if (puser.finished == False): History.new(event=History.REMAINDER, actor=puser.user, object=puser, authorized=[puser.user], related=[puser.processtask.process])
def resignRejectedUser(self, oldUser, newUser): tasks = ProcessTaskUser.all(processtask=self).filter(user=oldUser) exists = ProcessTaskUser.all(processtask=self).filter( user=newUser).count() if exists == 0 or int(oldUser) == int(newUser): for task in tasks: task.changeUser(newUser) History.new(event=History.ADD, actor=task.processtask.process.executioner, object=task.processtask.process, authorized=[newUser], related=[task.processtask.process]) else: for task in tasks: task.delete() self.save()
def warnLateDeadlines(): allProcess = Process.allWithDelay() for process in allProcess: ptasks = ProcessTask.all(process=process).filter( status=ProcessTask.RUNNING, deadline__lt=timezone.now()) for ptask in ptasks: if ((((ptask.deadline - timezone.now()).days + 1) % process.days_after_delay) == 0): pusers = ptask.users() for puser in pusers: if (puser.finished == False): History.new(event=History.LATE, actor=puser.user, object=puser, authorized=[puser.user], related=[puser.processtask.process])
def update(self, request, *args, **kwargs): """ Update an already existing form """ request.data[u'creator'] = request.user.id instance = self.get_object() serializer = FormSerializer(instance=instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) self.perform_update(serializer) History.new(event=History.EDIT, actor=request.user, object=instance) return Response(serializer.data)
def buy(request): profile = request.user.profile package = Package.objects.get(id=request.POST.get('id')) if package.price > profile.credits: return render(request, 'store/buy.html', {'success': False}) cards = Card.objects.get_random(package.cards_count) profile.cards.add(*cards) profile.credits -= package.price profile.save() history = History(user=request.user, text="Bought a new pack of " + package.cards_count.__str__() + " cards", type='store') history.save() return render(request, 'store/buy.html', {'success': True, 'package': package, 'cards': cards})
def create_history(history_type_dict, source_object=None, data=None): history_type = get_object_or_404(HistoryType, namespace=history_type_dict['namespace'], name=history_type_dict['name']) new_history = History(history_type=history_type) if source_object: new_history.content_object = source_object if data: new_dict = {} for key, value in data.items(): new_dict[key] = {} if isinstance(value, models.Model): new_dict[key]['value'] = serializers.serialize('json', [value]) elif isinstance(value, models.query.QuerySet): new_dict[key]['value'] = serializers.serialize('json', value) else: new_dict[key]['value'] = json.dumps(value) new_dict[key]['type'] = pickle.dumps(type(value)) new_history.dictionary = json.dumps(new_dict) new_history.save()
def test_convert_its_RST_text_to_HTML(self): h = History(text="*NSI* site rulz!") h.to_html() |should| contain('<em>NSI</em> site rulz!')
def parse_jabong(request): website = Website.objects.get(name="Jabong") brand = Brand.objects.get(name="Adidas") category = Category.objects.get(name="Shoes") url = 'http://www.jabong.com/men/shoes/men-sports-shoes/Adidas/?special_price=1&page=4' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = {} headers = { 'User-Agent': user_agent, 'X-Requested-With': 'XMLHttpRequest' } data = urllib.urlencode(values) req = urllib2.Request(url, data, headers) response = urllib2.urlopen(req) html = response.read() tree = lxml.html.fromstring(html) for el in tree.cssselect("li.itm a.itm-link"): print el.cssselect(".itm-title")[0].text.strip() try: search_item = Item.objects.get(name=el.cssselect(".itm-title")[0].text.strip()) except: search_item = None print search_item if search_item is None: print "Item does not exist. Creating new" item = Item() item.name = el.cssselect(".itm-title")[0].text.strip() print item.name item.gender_type = "MALE" product_url = el.attrib["href"] item.url = product_url item.category = category item.brand = brand item.website = website item.slug = slugify(item.name + "=" + item.website.slug) old_price_text = el.cssselect(".itm-price.old")[0].text new_price_text = el.cssselect(".itm-price.special-b")[0].text discount_rate_text = el.cssselect(".itm-price.discount")[0].text re_float = re.compile(r'.*?(?P<number>\d+\.?\d*).*?') old_price = re_float.match(old_price_text).group("number") new_price = re_float.match(new_price_text).group("number") discount_rate = re_float.match(discount_rate_text).group("number") user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = {} headers = { 'User-Agent': user_agent, } data = urllib.urlencode(values) req = urllib2.Request(product_url, data, headers) product_response = urllib2.urlopen(req) product_html = product_response.read() product_tree = lxml.html.fromstring(product_html) print product_tree print product_tree.cssselect(".prd-image") print product_tree.cssselect(".prd-image")[0].attrib["src"] item.image_url1 = product_tree.cssselect("#prdImage")[0].attrib["src"] item.details = product_tree.cssselect(".prd-description")[0].text item.save() history = History() history.item = item history.offer_text = item.brand.name + " " + item.name + " " + old_price_text + " " + new_price_text + " " + discount_rate_text history.selling_price = float(new_price) history.actual_price = float(old_price) history.discount_rate = float(discount_rate) history.is_on_sale = True history.save() print item print "#######################################" return HttpResponse(html)