def create_action(user, verb, target=None): """ :param user: Объект User :param verb: что сделал User :param target: target - определенная модель :return: True если небыло идентиных действий больше 1 минуты, False в обратном случае """ now = timezone.now() minute = timedelta(seconds=60) last_minute = now - minute # устанавливаем параметры (именованные аргументы) для фильтрации kwargs = { 'user_id': user.pk, 'verb': verb, 'created__gte': last_minute, # созданы менее минуты назад } # находим индентиные запросы, сохраненные в бд за последние 60 секунд similar_actions = Action.objects.filter(**kwargs) if target: target_ct = ContentType.objects.get_for_model(model=target) # находим идентичные запросы если был target similar_actions = similar_actions.filter(target_ct=target_ct, target_id=target.pk) if not similar_actions: # если идентичных запросов не было хотя бы минуту - сохраняем новые в бд и возвращаем True action = Action(user=user, verb=verb, target=target) action.save() return True # в противном слуае вернем False return False
def enzyme_office_delete(request, id): commentlist = models.comment.objects.all() #check the user is admin or not if request.session['is_login'] is True and request.session[ 'role'] == 'admin': if request.method == 'POST': id = request.POST['id'] id = int(id) # log the action # log the action user = User.objects.get(username=request.session.get("username")) action = Action(user=user, verb="delete one of the comment", target=None) action.save() models.comment.objects.filter(id=id).delete() messages.add_message(request, messages.WARNING, "You successfuly delete your comment") return enzyme_office_dashboard(request) deletecomment = [] for comment in commentlist: if int(comment.id) is id: deletecomment.append(comment) return render(request, "enzymeoffice/enzyme/delete.html", {"editlist": deletecomment}) else: enzyme_office_dashboard(request)
def handle(self, *args, **options): referrals = Referral.objects.filter( status=Referral.REFERRAL_STATUS_CHOICES.referred, expire_date__lt=date.today(), response_date__isnull=True) for r in referrals: self.stdout.write( 'Setting referral status to "expired": {}'.format(r)) logger.info('Setting referral status to "expired": {}'.format(r)) r.status = Referral.REFERRAL_STATUS_CHOICES.expired r.save() # Check the referral's application: if it is status 'with_referee' # but has no referral's that are status 'referred', then set the # application status to 'with admin'. app = r.application if not Referral.objects.filter( application=app, status=Referral.REFERRAL_STATUS_CHOICES.referred).exists(): self.stdout.write( 'Setting application status to "with admin": {}'.format( app)) logger.info( 'Setting application status to "with admin": {}'.format( app)) app.state = app.APP_STATE_CHOICES.with_admin app.save() # Record an action. action = Action( content_object=app, action= '[SYSTEM] No outstanding referrals, application status set to {}' .format(app.get_state_display())) action.save() return
def form_valid(self, form): self.object = form.save(commit=False) app = self.get_object() status = self.kwargs['status'] self.object.status = ApprovalModel.APPROVAL_STATE_CHOICES.__getattr__(status) self.object.save() action = Action( content_object=app, category=Action.ACTION_CATEGORY_CHOICES.change, user=self.request.user, action='Approval Change') action.save() return super(ApprovalStatusChange, self).form_valid(form)
def create_action(user, verb, target=None): now = timezone.now() last_minute = now - datetime.timedelta(seconds=60) similar_actions = Action.objects.filter(user_id=user.id, verb=verb, created__gte=last_minute) if target: target_ct = ContentType.objects.get_for_model(target) similar_actions = similar_actions.filter(target_ct=target_ct, target_id=target.id) if not similar_actions: action = Action(user=user, verb=verb, target=target) action.save() return True return False
def on_tweet(data): try : tweet = json.loads(data) content = tweet['text'] content = insensitive_hippo.sub('', content ) action = Action() action.content = content[:70] action.from_ip = 'Twitter' print (action.content) action.save() print ( action.id ) except : return
def form_valid(self, form): self.object = form.save(commit=False) app = self.get_object() status = self.kwargs['status'] self.object.status = ApprovalModel.APPROVAL_STATE_CHOICES.__getattr__( status) self.object.save() action = Action(content_object=app, category=Action.ACTION_CATEGORY_CHOICES.change, user=self.request.user, action='Approval Change') action.save() if status == 'surrendered': emailcontext = {'approval_id': app.id, 'app': app} emailGroup('Approval surrendered AP-' + str(app.id), emailcontext, 'approval_surrendered.html', None, None, None, 'Statdev Processor') return super(ApprovalStatusChange, self).form_valid(form)
def enzyme_office_edit(request, id): commentlist = models.comment.objects.all() if request.session['is_login'] is True: a = request.POST if request.method == 'POST': name = request.POST['name'] Age = request.POST['age'] comments = request.POST['commentedit'] id = request.POST['id'] for comment in commentlist: if comment.id == int(id): if (comment.comment != comments): # log the action user = User.objects.get( username=request.session.get("username")) action = Action(user=user, verb="Edit the comment's comment", target=comment) action.save() comment.comment = comments if (comment.name != name): # log the action user = User.objects.get( username=request.session.get("username")) action = Action(user=user, verb="Edit the commenter", target=comment) action.save() comment.name = name if (comment.Age != Age): # log the action user = User.objects.get( username=request.session.get("username")) action = Action(user=user, verb="Edit the commenter AGE", target=comment) action.save() comment.Age = Age comment.save() messages.add_message(request, messages.INFO, "You successfuly edit your comment") return enzyme_office_dashboard(request) editcomment = [] #get target comment and edit it for i in range(len(commentlist)): if int(commentlist[i].id) is id: editcomment.append(commentlist[i]) return render(request, "enzymeoffice/enzyme/edit.html", {"editlist": editcomment}) else: enzyme_office_alternative(request)
def create_action(user, verb, target=None): # Sprawdzenie pod kątem podobnej akcji przeprowadzonej w ciągu ostatniej minuty. # aby nie dodawać obiektów związanych z kliknięciem oraz odkliknięiem czegoś. # Jeżeli w ciągu ostatniej minuty nie była przeprowadzona identyczna akcja, # tworzymy nowy obiekt Action. Jeżeli został utworzony obiekt Action, # wartością zwrotną metody jest True, w przeciwnym razie False. # web_pdb.set_trace() now = timezone.now() last_minute = now - datetime.timedelta(seconds=60) similar_actions = Action.objects.filter( user_id=user.id, verb= verb, created__gte=last_minute) if target: target_ct = ContentType.objects.get_for_model(target) similar_actions = similar_actions.filter(target_ct=target_ct, target_id=target.id) # is there is no similar_actions if not similar_actions: # Nie znaleziono żadnych akcji, podobnych do podanej action = Action(user=user, verb=verb, target=target) action.save() return True return False
def setup(request, action_type=None): if action_type and action_type not in action_mapping.keys(): raise Exception("Unknown action type: %s" % action_type) if request.method == "POST" and 'action' in request.POST: if request.POST['action'] == "delete": a = Action.objects.get(user=request.user, id=request.POST['id']) a.delete() return HttpResponseRedirect("/actions/") if request.method == "POST" and not action_type: raise Exception("POST requires action_type (got %s)" % action_type) if request.method == "POST": a = Action( user=request.user, action_type=action_type, data = request.POST.get('data', "") ) a.save() return HttpResponseRedirect("/actions/") if action_type: return render(request, "actions/%s.html" % action_type) k = AccessKey.objects.get(user=request.user) actions = Action.objects.filter(user=request.user) return render(request, "actions/list.html", {'actions': actions, 'key': k.key})
def action(plan): action = Action(plan=plan, name='Test action 1', identifier='t1') action.official_name = action.name action.save() return action
def savecomment(request): is_ajax = request.headers.get('x-requested-with') == 'XMLHttpRequest' commentlist = models.comment.objects.all().order_by('id') if is_ajax and request.method == "POST" and request.session['is_login']: title = request.POST.get('work') try: a = request.POST id = request.POST['id'] ide = str(id) age = request.POST['age'] name = request.POST['name'] workhere = request.POST['work'] comment = request.POST['text'] username = request.session['username'] id = commentlist[len(commentlist) - 1].id + 1 nc = models.comment(name=name, Age=age, id=id, work=workhere, username=username, comment=comment, date_posted=date.today()) nc.save() #save to database user = User.objects.get(username=request.session.get("username")) #log the action action = Action(user=user, verb="created the new comment", target=nc) action.save() messages.add_message(request, messages.SUCCESS, "You successfuly submit your comment") # meassage # Azure Translator worklocation = work.objects.get(title=workhere).country if worklocation == "Russian": endpoint = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en&to=ru' elif worklocation == "Thai": endpoint = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en&to=th' elif worklocation == "Japan": endpoint = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en&to=ja' headers = { # Request headers 'Content-Type': 'application/json; charset=UTF-8', 'Ocp-Apim-Subscription-Key': 'aadbb069b24b45a3807f56b5b2357af6', } body = [{'text': comment}] respons = requests.post(endpoint, headers=headers, json=body) respons_json = respons.json() aftersave = [] if type(respons_json) is dict: #prevent error commentlist = models.comment.objects.filter( work=workhere).order_by('id') for comments in commentlist: aftersave.append(comments.name + " : " + comments.comment) aftersave.append( "you save successfully, but somethings wrong with the Microsoft Azure" ) else: langcomment = respons_json[0]['translations'][0]['text'] commentlist = models.comment.objects.filter( work=workhere).order_by('id') for comments in commentlist: if comments.comment == comment: aftersave.append(comments.name + " : " + comments.comment + " Author's Language: " + langcomment) else: aftersave.append(comments.name + " : " + comments.comment) return JsonResponse( { 'success': 'success', 'commentlist': aftersave }, status=200) except models.comment.DoesNotExist: return JsonResponse({'error': 'No comment with the work'}, status=200) else: return JsonResponse({'error': 'Invaild Ajax request'}, status=400)