def repo_online_gc(request, repo_id): if request.method != 'POST': raise Http404 repo = get_repo(repo_id) if not repo: raise Http404 referer = request.META.get('HTTP_REFERER', None) next = settings.SITE_ROOT if referer is None else referer username = request.user.username if is_org_context(request): repo_owner = seafile_api.get_org_repo_owner(repo.id) else: repo_owner = seafile_api.get_repo_owner(repo.id) is_repo_owner = True if repo_owner == username else False if not is_repo_owner: messages.error(request, _('Permission denied')) return HttpResponseRedirect(next) day = int(request.POST.get('day')) try: seafile_api.clean_up_repo_history(repo.id, day) except SearpcError as e: logger.error(e) messages.error(request, _('Internal server error')) return HttpResponseRedirect(next) return HttpResponseRedirect(next)
def create_saved_search(request, database_name=settings.MONGO_DB_NAME, collection_name=settings.MONGO_MASTER_COLLECTION, skip=0, limit=200, return_keys=()): name = _("Create a Saved Search") if request.method == 'POST': form = SavedSearchForm(request.POST) if form.is_valid(): ss = form.save(commit = False) ss.user = request.user ss.save() return HttpResponseRedirect(reverse('saved_searches')) else: #The form is invalid messages.error(request,_("Please correct the errors in the form.")) return render_to_response('generic/bootstrapform.html', {'form': form, 'name':name, }, RequestContext(request)) #this is a GET idata ={'database_name': database_name, 'collection_name': collection_name} context= {'name':name, 'form': SavedSearchForm(initial=idata) } return render_to_response('generic/bootstrapform.html', RequestContext(request, context,))
def object_action(self, form, instance): try: if instance.is_superuser or instance.is_staff: messages.error( self.request, _( 'Super user and staff user password ' 'reseting is not allowed, use the admin ' 'interface for these cases.' ) ) else: instance.set_password(form.cleaned_data['new_password_1']) instance.save() messages.success( self.request, _( 'Successfull password reset for user: %s.' ) % instance ) except Exception as exception: messages.error( self.request, _( 'Error reseting password for user "%(user)s": %(error)s' ) % { 'user': instance, 'error': exception } )
def group_add_edit(request, url=None): """ Add or edit a group. (If a url is passed in, we're editing.) """ profile = request.user.userprofile if url: # Get the group to edit group = get_object_or_404(Group, url=url) # Only a group curator or an admin is allowed to edit a group is_curator = profile == group.curator if not (is_curator or request.user.is_superuser): messages.error(request, _('You must be a curator or an admin to edit a group')) return redirect(reverse('groups:show_group', args=[group.url])) else: group = Group(curator=profile) form_class = SuperuserGroupForm if request.user.is_superuser else GroupForm form = form_class(request.POST or None, instance=group) if form.is_valid(): group = form.save() # Ensure curator is in the group when it's created if profile == group.curator and not group.has_member(profile): group.add_member(profile) return redirect(reverse('groups:show_group', args=[group.url])) context = { 'form': form, 'creating': url is None, 'group': group if url else None, } return render(request, 'groups/add_edit.html', context)
def edit_event(request, event_id): event = get_event_by_id(event_id) user = request.user initial = get_initial_data(event) initial['user_email'] = request.user.email event_data = {} if request.method == 'POST': event_form = AddEventForm(data=request.POST, files=request.FILES) else: event_form = AddEventForm(initial=initial) existing_picture = event.picture if event_form.is_valid(): # picture_check works with jasny bootstrap magix picture_check = request.POST.get('picture') picture = request.FILES.get('picture', None) event_data = event_form.cleaned_data event_data['creator'] = request.user # checking if user entered a different email than in her profile if user.email != event_data['user_email']: update_user_email(user.id, event_data['user_email']) event_data.pop('user_email') try: if picture: if picture.size > (256 * 1024): raise ImageSizeTooLargeException('Image size too large.') event_data['picture'] = process_image(picture) elif picture_check == "nochange": event_data['picture'] = existing_picture else: del event_data['picture'] create_or_update_event(event_id, **event_data) return HttpResponseRedirect( reverse( 'web.view_event', kwargs={ 'event_id': event.id, 'slug': event.slug})) except ImageSizeTooLargeException: messages.error( request, 'The image is just a bit too big for us (must be up to 256 kb). ' 'Please reduce your image size and try agin.') except UploadImageError as e: messages.error(request, e.message) return render_to_response( 'pages/add_event.html', { 'form': event_form, 'address': event_data.get('location', None), 'editing': True, 'picture_url': event.picture, }, context_instance=RequestContext(request))
def borrar_tipotelefonos(self, request, queryset): """ borra los tipos de telefonos seleccionados solo si no estan asociados a un telefono """ deleted='' nonDeleted='' for f in queryset: if not f.telefono_set.all(): f.delete() deleted+=f.nombre+', ' else: nonDeleted+=f.nombre+', ' if deleted: deleted = deleted[:-2] msg1 = u'Se eliminaron los siguientes tipo de teléfono: %s.' %\ deleted self.message_user(request, msg1) if nonDeleted: msg2 = u'Recuerde que sólo se pueden eliminar los tipos de teléfono \ que no estén asociados a ningún número telefónico.' messages.warning(request,msg2) nonDeleted = nonDeleted[:-2] msg3 = u'Los siguientes tipos de teléfono no fueron eliminados: %s.'\ % nonDeleted messages.error(request,msg3)
def user_list(request): context = RequestContext(request) if request.method == 'POST': form = forms.FindUserForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') try: user = models.User.objects.get(username=username) return redirect('kegadmin-edit-user', user.id) except models.User.DoesNotExist: messages.error(request, 'User "%s" does not exist.' % username) users = models.User.objects.exclude(username='******').order_by('-id') paginator = Paginator(users, 25) page = request.GET.get('page') try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) context['users'] = users return render_to_response('kegadmin/user_list.html', context_instance=context)
def answer(request): ans = "" if request.method == 'POST': ans = request.POST.get('ans') player = models.player.objects.get(user_id=request.user.pk) try: level = models.level.objects.get(l_number=player.max_level) except: return render(request, 'finish.html', {'player': player}) # print answer # print level.answer if ans == level.answer: #print level.answer player.max_level = player.max_level + 1 player.score = player.score + 10 player.timestamp = datetime.datetime.now() level.numuser = level.numuser + 1 level.save() #print level.numuser # print player.max_level global m_level global f_user # print f_user # print m_level if m_level < player.max_level: m_level = player.max_level f_user = player.name player.save() try: level = models.level.objects.get(l_number=player.max_level) return render(request, 'level.html', {'player': player, 'level': level}) except: return render(request, 'finish.html', {'player': player}) messages.error(request, "Wrong Answer!, Try Again") return render(request, 'level.html', {'player': player, 'level': level})
def _apply_changes(request, old_status, new_status): """Try to apply changes and handle errors.""" try: __apply_changes(request, old_status, new_status) except ActionError as exception: messages.error(request, _('Action error: {0} [{1}] [{2}]').format( exception.args[0], exception.args[1], exception.args[2]))
def edit(request, petreport_id): pet_report = get_object_or_404(PetReport, pk=petreport_id) if request.method == "GET": form = PetReportForm(instance=pet_report) elif request.method == "POST": form = PetReportForm(request.POST, request.FILES) if form.is_valid() == True: pr = form.save(commit=False) pet_report.update_fields(pr, request=request.POST) messages.success(request, "You've successfully updated your pet report.") return redirect(URL_PRDP + "%d/" % pet_report.id) form = PetReportForm(instance=pet_report) messages.error(request, "Something went wrong. Please check the fields and try again.") else: raise Http404 return render_to_response(HTML_EDIT_PETREPORT, { "form": form, "petreport": pet_report, "RECAPTCHA_CLIENT_SECRET": settings.RECAPTCHA_CLIENT_SECRET, "PETREPORT_TAG_INFO_LENGTH":PETREPORT_TAG_INFO_LENGTH, "PETREPORT_DESCRIPTION_LENGTH":PETREPORT_DESCRIPTION_LENGTH, "PETREPORT_CONTACT_NAME_LENGTH": PETREPORT_CONTACT_NAME_LENGTH, "PETREPORT_CONTACT_NUMBER_LENGTH": PETREPORT_CONTACT_NUMBER_LENGTH, "PETREPORT_CONTACT_EMAIL_LENGTH": PETREPORT_CONTACT_EMAIL_LENGTH, "PETREPORT_CONTACT_LINK_LENGTH": PETREPORT_CONTACT_LINK_LENGTH }, RequestContext(request))
def post_message(request,to): from_user = request.user to_user = get_object_or_404(User,username=to) if from_user==to_user: # messages.error(request,'can not write email to yourself') messages.error(request,_(u'Вы не можете написать сообщение самому себе')) return HttpResponseRedirect(request.META['HTTP_REFERER']) #get existed chat chat= Chat.objects.filter(from_user=from_user,to_user=to_user) or Chat.objects.filter(to_user=from_user,from_user=to_user) if chat: chat=chat[0] #if chat first time then create it if not chat: chat=Chat.objects.create(from_user=from_user,to_user=to_user) if chat.from_user==from_user: chat.is_to_user_read=True else: chat.is_from_user_read=True file = request.FILES['file'] if 'file' in request.FILES else None chat.add_message(from_user,request.POST['message'],file=file) UserLog.objects.create(user=to_user, text_en='Got <a href="/show_chat/%s/">message</a> %s from user %s'%(request.user,request.POST['message'],request.user), text_ru=u'Получено <a href="/show_chat/%s/">сообщениe</a> %s от пользователя %s'%(request.user,request.POST['message'],request.user)) sendEmail(user=to_user,type='message',extra={'from':request.user,'message':request.POST['message']}) SystemLog.objects.create(user=to_user, text='Message %s from user %s to user %s'%(request.POST['message'],request.user,to_user)) return HttpResponseRedirect(reverse('send_message',args=[to,]))
def create_organism(request): if request.method == 'POST': form = CreateOrganismForm(data = request.POST) if form.is_valid(): query_dict = { "method" : "add_organism", "key": request.user.sessionkey, "params" : { "data" : { "name": form.cleaned_data['name'] } } } content_dict = api_request(query_dict) if content_dict.has_key('result'): cache.delete('organisms') messages.success(request, 'Organism "{}" successfully create.'.format(form.cleaned_data['name'])) elif content_dict.has_key('error'): messages.error(request, 'ERROR: {}'.format(content_dict['error']['message'])) else: form = CreateOrganismForm() template_context = {'form': form,} return render_to_response('create_organism.html', template_context, context_instance=RequestContext(request))
def send_mail_to_owners(self, request, queryset): for momend in queryset: _successful = DataManagerUtil.send_momend_created_email(momend) if _successful: messages.success(request, 'Successful: '+str(momend.id)) else: messages.error(request, 'Error: '+str(momend.id))
def downloadxlsall(request): import datetime from CLAT.services import xls_engine if request.is_ajax() and request.method == 'GET': try: options = { '1' : { 'model' : CourseDetail, 'nameoffile' : 'allcourses'}, '2' : { 'model' : Teacher, 'nameoffile' : 'allteachers'}, '3' : { 'model' : Student, 'nameoffile' : 'allstudents'} } optionselected = str(request.GET.get('_option')) _list = options[optionselected]['model'].objects.all() if _list: if optionselected == '1': wb = xls_engine.all_courses(_list) if optionselected == '2': wb = xls_engine.all_teachers(_list) if optionselected == '3': wb = xls_engine.all_students(_list) file_dir_path = 'xls/'+options[optionselected]['nameoffile'] if not os.path.exists(file_dir_path): os.makedirs(file_dir_path) assert wb,'AssertError: Work sheet not generated' wb.save(file_dir_path + '/' + options[optionselected]['nameoffile'] +'.xls') return HttpResponse(json.dumps([True,options[optionselected]['nameoffile']]), content_type="application/json") except Exception as e: print e.args messages.error(request,'Unable to generate excel file.Try again.') return HttpResponse(json.dumps([False,None]), content_type="application/json") return HttpResponse(json.dumps([False,None]), content_type="application/json")
def download_xls(request, course_uuid): course = CourseDetail.objects.get(course_uuid = course_uuid, teacher = request.user) # user_list = [] if course: _users_enroll_course = EnrolledCourses.objects.filter(course = course) # user_list = [enroll_course.user for enroll_course in _users_enroll_course] try: assert _users_enroll_course,'Assert Error: Not have any user' except Exception as e: messages.info(request, 'Unable to find enrolled user(s) in this course.') return redirect('/teacher/manage/'+course_uuid) _sm_course_name = 'course_id_'+str(course.id) if create_users_xls(users_enroll_course = _users_enroll_course, _sm_course_name = _sm_course_name, course_name = course.course_name): dir_name = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) file_dir_path = 'xls/'+_sm_course_name filename = dir_name+'/'+file_dir_path+'/enrolled_user.xls' wrapper = FileWrapper(file(filename)) response = HttpResponse(wrapper, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(filename) response['Content-Length'] = os.path.getsize(filename) return response else: messages.error(request,'Error in your request please try again after some time.') return redirect('/teacher/manage/'+course_uuid)
def teacher_login(request): if request.user.is_authenticated(): messages.info(request,'Please logout first and then re-login with a different account.') return HttpResponseRedirect('/home/') if request.method == 'POST': t_username = request.POST.get('username') t_password = request.POST.get('password') try: t_user = authenticate(username=t_username, password=t_password) teacher = Teacher.objects.get(pk=t_user.id) except Exception as e: t_user = None teacher = None if teacher is not None: if t_user.is_active: login(request, t_user) messages.success(request,'You logged in successfully.') return HttpResponseRedirect('/teacher/') else: messages.warning(request,'Your account is not yet active.') return render(request, 'teacher/login_teacher.html', {'t_not_active': True, 'next': request.POST.get('next')}) else: course_list = CourseDetail.objects.all() course_list = pagination.get_paginated_list(obj_list=course_list,page = request.GET.get('page')) messages.error(request,'Please enter valid credentials.') return render(request, 'teacher/login_teacher.html', {'t_login_error': True, 'next': request.POST.get('next')}) else: return render(request,'teacher/login_teacher.html',{})
def update_course_details(request): if request.method == 'POST' and request.is_ajax(): course_description = '\n'+request.POST.get('_c_desc').strip() course_objective = '\n'+request.POST.get('_c_objve').strip() course_eligibility = '\n'+request.POST.get('_c_eligbty').strip() course_crt_benefits = '\n'+request.POST.get('_c_cbf').strip() course_short_desc = '\n'+request.POST.get('_c_csd').strip() if len(course_description)<10 or len(course_objective) < 10 or len(course_eligibility) < 10: messages.error(request,'All 3 fields must have at least 10 characters.') return HttpResponse(json.dumps(True), content_type="application/json") course = CourseDetail.objects.get(course_uuid=request.POST.get('_c_id')) if course: try: course.course_information.description = course_description course.course_information.objective = course_objective course.course_information.crt_benefits = course_crt_benefits course.course_information.eligibility = course_eligibility course.course_information.short_description = course_short_desc course.course_information.save() messages.success(request,'Course details updated.') return HttpResponse(json.dumps(True), content_type="application/json") except Exception as e: CourseInformation.objects.create(course = course,course_description=course_description,course_objective=course_objective) return HttpResponse(json.dumps(False), content_type="application/json")
def delete(self, request, *args, **kwargs): self.object = self.get_object() track_deleted_objects = getattr(settings, 'PRAGMATIC_TRACK_DELETED_OBJECTS', False) try: if track_deleted_objects: # prepare tracking data content_type = ContentType.objects.get_for_model(self.object, for_concrete_model=False) object_id = self.object.id object_str = str(self.object) user = self.request.user # delete object self.object.delete() # show success message if available if self.message_success: messages.success(request, self.message_success) if track_deleted_objects: # track deleted object DeletedObject.objects.create( content_type=content_type, object_id=object_id, object_str=object_str, user=user if user.is_authenticated else None ) return HttpResponseRedirect(self.get_success_url()) except ProtectedError: if self.message_error: messages.error(request, self.message_error) return HttpResponseRedirect(self.get_failure_url())
def login_user(request): d = {} if request.user.is_authenticated(): #already logged in return HttpResponseRedirect('/accounts/profile') form = LoginForm(request.POST or None) d['login_form'] = form d['next'] = request.GET.get('next', '/accounts/profile') if request.method == 'POST': #submitting form if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) if user is not None: if user.is_active: #all good, log user in login(request, user) return HttpResponseRedirect(request.POST.get('next')) else: #account disabled return HttpResponseRedirect('/accounts/disabled') else: #authenticate failed messages.error(request, '<b>Error:</b> Login failed, please try again.') return render(request, 'accounts/login.html', d) else: #invalid form messages_from_form(request, form) return render(request, 'accounts/login.html', d) else: #display empty form return render(request, 'accounts/login.html', d)
def profile_create(request): context = RequestContext(request) if request.user.is_authenticated(): userid = int(request.user.id) queryset = profiles.objects.filter(user=userid) if queryset: messages.error(request, "You have already created a profile!") return HttpResponseRedirect('/profiles/myprofile/') form = Profileregister(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() if instance.pId == "TMG": instance.pId = "TMG" + "00" + str(instance.tmId) instance.save() messages.add_message(request,messages.SUCCESS,"Successfully created a profile!") return HttpResponseRedirect("/profiles/myprofile") else: form = Profileregister(request.POST or None, request.FILES or None) content = { "form": form, "title": "Create/Register" } return render(request, "register.html", content)
def direct_messages_details(request, sender_id): """ method to accept new directmessage. accepts only post request. :param request: :return: """ if request.method == "POST": # look for posted text message_content = request.POST.get("text", False) if (not message_content) or len(message_content) < 1: # if there is no text or the text is too short redirect and show error messages.error(request, "Kein Text angegeben") return HttpResponseRedirect(reverse("home")) # create a new direct message and fill in data, then save it, if successful message_var = Directmessage() message_var.creator = request.user message_var.created = datetime.now() message_var.text = message_content try: message_var.receiver = User.objects.get(username=sender_id) except ObjectDoesNotExist: messages.error(request, "Den Empfaenger gibt es nicht") return HttpResponseRedirect(reverse("home")) message_var.save() return HttpResponseRedirect("%s?active_conversation=%s" % (reverse("all_chats"), message_var.receiver.username))
def post(self, *args, **kwargs): to = self.request.POST.get('status', '') if self.order.status in (Order.STATUS_PENDING, Order.STATUS_EXPIRED) and to == 'p': try: mark_order_paid(self.order, manual=True, user=self.request.user) except Quota.QuotaExceededException as e: messages.error(self.request, str(e)) else: messages.success(self.request, _('The order has been marked as paid.')) elif self.order.status == Order.STATUS_PENDING and to == 'c': cancel_order(self.order, user=self.request.user) messages.success(self.request, _('The order has been cancelled.')) elif self.order.status == Order.STATUS_PAID and to == 'n': self.order.status = Order.STATUS_PENDING self.order.payment_manual = True self.order.save() self.order.log_action('pretix.event.order.unpaid', user=self.request.user) messages.success(self.request, _('The order has been marked as not paid.')) elif self.order.status == Order.STATUS_PENDING and to == 'e': self.order.status = Order.STATUS_EXPIRED self.order.save() self.order.log_action('pretix.event.order.expired', user=self.request.user) messages.success(self.request, _('The order has been marked as expired.')) elif self.order.status == Order.STATUS_PAID and to == 'r': ret = self.payment_provider.order_control_refund_perform(self.request, self.order) if ret: return redirect(ret) return redirect(self.get_order_url())
def __call__(self): if self.request.method == 'POST': _deletable_objects = self.request.POST.getlist('selected_objects') for _d_o in _deletable_objects: _obj = MyPluginModel.objects.get(pk=_d_o) log.debug("%s deleted MyPluginModel %s" % (self.request.user, _obj.name)) _obj.delete() _obj = None messages.success(self.request, _("Deleted My Plugin Model")) return HttpResponseRedirect(reverse('my_plugin_models')) else: log.debug("%s about to delete MyPluginModel" % self.request.user) _deletable_objects = self.request.GET.getlist('selected_objects') if len(_deletable_objects) < 1: messages.error(self.request, _("Please pick a My Plugin Model to delete")) return HttpResponseRedirect(reverse('my_plugin_models')) objects = [] for (counter, i) in enumerate(_deletable_objects): try: objects.append(MyPluginModel.objects.get(pk=i)) except MyPluginModel.DoesNotExist: messages.error(self.request, _("Tried to delete a My Plugin Model which didn't exist")) return HttpResponseRedirect(reverse('my_plugin_models')) ctx = { "deletable_objects": _deletable_objects, "object_name": _("My Plugin Model"), "objects":objects} return self.main(self.request, self.template, ctx)
def dispatch(self, request, *args, **kwargs): from pretix.base.services.cart import error_messages err = None v = request.GET.get('voucher') if v: v = v.strip() try: self.voucher = Voucher.objects.get(code=v, event=request.event) if self.voucher.redeemed: err = error_messages['voucher_redeemed'] if self.voucher.valid_until is not None and self.voucher.valid_until < now(): err = error_messages['voucher_expired'] except Voucher.DoesNotExist: err = error_messages['voucher_invalid'] else: return redirect(eventreverse(request.event, 'presale:event.index')) if request.event.presale_start and now() < request.event.presale_start: err = error_messages['not_started'] if request.event.presale_end and now() > request.event.presale_end: err = error_messages['ended'] if err: messages.error(request, _(err)) return redirect(eventreverse(request.event, 'presale:event.index')) return super().dispatch(request, *args, **kwargs)
def begin(self, request, data): try: openid_url = data['openid_url'].strip() except KeyError: messages.error(request, lang.FILL_OPENID_URL) return redirect('netauth-login') # allow user to type openid provider without http:// prefix if not openid_url.startswith("http"): openid_url = "http://%s" % openid_url return_url = request.build_absolute_uri(reverse('netauth-complete', args=[self.provider])) request.session['openid_return_to'] = return_url client = consumer.Consumer(request.session, None) try: openid_request = client.begin(openid_url) sreg_extra = [value for __, value in self.PROFILE_MAPPING.items()] sreg = SRegRequest(required=sreg_extra) openid_request.addExtension(sreg) ax_msg = FetchRequest() for __, detail in self.PROFILE_MAPPING.items(): ax_msg.add(AttrInfo(settings.AX_URIS[detail], required=True)) openid_request.addExtension(ax_msg) redirect_url = openid_request.redirectURL(realm='http://' + request.get_host(), return_to=return_url) return redirect(redirect_url) except discover.DiscoveryFailure: messages.error(request, _('Could not find OpenID server')) return redirect('netauth-login')
def edit_center(request, slug=None): center = Center.objects.get(slug=slug) ImageFormSet = modelformset_factory(CenterPhoto, form=ImageForm) if request.user.is_merchant: if request.method == 'POST': form = CenterForm(request.POST, instance=center) formset = ImageFormSet(request.POST, request.FILES, queryset=CenterPhoto.objects.filter(center=center)) if form.is_valid() and formset.is_valid(): form.save() for form in formset: try: image = form.cleaned_data['image'] photo = CenterPhoto(center=center, image=image) photo.user_id = request.user.id photo.save() except: messages.error(request, 'Technical error') return render(request, "updated_center.html", locals()) else: form = CenterForm(instance=center) formset = ImageFormSet(queryset=CenterPhoto.objects.filter(center=center)) return render(request, 'center_edit.html', {'form': form, 'formset': formset}) else: messages.add_message( request, messages.ERROR, 'You are not allowed to edit this center. Contact an eventdiary admin' ) return redirect(reverse('center_listing'))
def post(request): Rule.objects.filter(user__exact=request.user).delete() prefixes = filter( lambda k: k.endswith('-keyword') and not k.startswith('{prefix}'), request.POST ) prefixes = [k.split('-')[0] for k in prefixes] try: prefixes.sort(key=int) except ValueError: messages.error(request, """ There was an invalid input name in your request. You can try again, but please contact us if the problem persists. """) i = 0 for prefix in prefixes: # Empty? if not request.POST.get('%s-%s' % (prefix, 'keyword'), ''): continue form = {} for field in Rule._meta.fields: # Ignored fields if field.name in ('id', 'user', 'index'): continue postname = '%s-%s' % (prefix, field.name) form[field.name] = request.POST.get(postname, False) r = Rule(user=request.user, index=i, **form) r.save() i += 1 return redirect('/rules')
def handle(self, request, data): values = {} values['orig_cont'] = data['orig_container_name'] values['orig_obj'] = data['orig_object_name'] values['new_cont'] = data['new_container_name'] values['new_obj'] = data['new_object_name'] escaped = {} for key, value in values.iteritems(): escaped[key] = value.encode('utf-8').replace('/', '%2F') #escaped[key] = value.encode('utf-8') try: api.swift_copy_object(request, escaped['orig_cont'], escaped['orig_obj'] , escaped['new_cont'], escaped['new_obj'], request.session.get('storage_url', None)) messages.success(request, 'Object was successfully copied to %s/%s' % (values['new_cont'], values['new_obj'])) except NoSuchContainer, e: messages.error(request, 'Object copy is failed. %s' % str(e))
def _items_from_post_data(self): """ Parses the POST data and returns a list of tuples in the form (item id, variation id or None, number) """ # Compatibility patch that makes the frontend code a lot easier req_items = list(self.request.POST.lists()) if '_voucher_item' in self.request.POST and '_voucher_code' in self.request.POST: req_items.append(( '%s_voucher' % self.request.POST['_voucher_item'], (self.request.POST['_voucher_code'],) )) pass items = [] for key, values in req_items: for value in values: try: item = self._item_from_post_value(key, value) except CartError as e: messages.error(self.request, str(e)) return if item: items.append(item) if len(items) == 0: messages.warning(self.request, _('You did not select any products.')) return [] return items
def get(self, request, matchday_games_id, *args, **kwargs): if int(matchday_games_id) is 1: coral_json = "/games_odds/static/json/coral_get_matches_0.json" adjust_matches_2 = self.get_coral_match_day_games( self.coral_db_match_list[0], self.coral_db_odds_list[0], matchday_games_id, coral_json) if adjust_matches_2 is not None: context = { 'match_day': True, 'adjust_matches': adjust_matches_2, } return render(request, self.template_name_0, self.get_context_data(**context)) else: get_coral_daily_matches = self.save_coral_matches_and_odds( self.coral_db_match_list[0], self.coral_db_odds_list[0], matchday_games_id, self.coralUrl) if self.coral_db_match_list[0].objects.count( ) >= 1 and self.coral_db_odds_list[0].objects.count() >= 1: messages.success( request, 'Saving into ' + get_coral_daily_matches + ' was successfully saved into Database') return redirect('bookies') if int(matchday_games_id) is 2: coral_json = "/games_odds/static/json/coral_get_matches_1.json" adjust_matches_2 = self.get_coral_match_day_games( self.coral_db_match_list[1], self.coral_db_odds_list[1], matchday_games_id, coral_json) if adjust_matches_2 is not None: context = { 'match_day': True, 'adjust_matches': adjust_matches_2, } return render(request, self.template_name_1, self.get_context_data(**context)) else: get_coral_daily_matches = self.save_coral_matches_and_odds( self.coral_db_match_list[1], self.coral_db_odds_list[1], matchday_games_id, self.coralUrl) if self.coral_db_match_list[1].objects.count( ) >= 1 and self.coral_db_odds_list[1].objects.count() >= 1: messages.success( request, 'Saving into ' + get_coral_daily_matches + ' was successfully saved into Database') return redirect('bookies') if int(matchday_games_id) is 3: coral_json = "/games_odds/static/json/coral_get_matches_2.json" adjust_matches_2 = self.get_coral_match_day_games( self.coral_db_match_list[2], self.coral_db_odds_list[2], matchday_games_id, coral_json) if adjust_matches_2 is not None: context = { 'match_day': True, 'adjust_matches': adjust_matches_2, } return render(request, self.template_name_2, self.get_context_data(**context)) else: get_coral_daily_matches = self.save_coral_matches_and_odds( self.coral_db_match_list[2], self.coral_db_odds_list[2], matchday_games_id, self.coralUrl) if self.coral_db_match_list[2].objects.count( ) >= 1 and self.coral_db_odds_list[2].objects.count() >= 1: messages.success( request, 'Saving into ' + get_coral_daily_matches + ' was successfully saved into Database') return redirect('bookies') if int(matchday_games_id) is 4: coral_json = "/games_odds/static/json/coral_get_matches_3.json" adjust_matches_2 = self.get_coral_match_day_games( self.coral_db_match_list[3], self.coral_db_odds_list[3], matchday_games_id, coral_json) if adjust_matches_2 is not None: context = { 'match_day': True, 'adjust_matches': adjust_matches_2, } return render(request, self.template_name_3, self.get_context_data(**context)) else: get_coral_daily_matches = self.save_coral_matches_and_odds( self.coral_db_match_list[3], self.coral_db_odds_list[3], matchday_games_id, self.coralUrl) if self.coral_db_match_list[3].objects.count( ) >= 1 and self.coral_db_odds_list[3].objects.count() >= 1: messages.success( request, 'Saving into ' + get_coral_daily_matches + ' was successfully saved into Database') return redirect('bookies') messages.error( request, 'The Match day ID do not match, please try again for Coral') return redirect('bookies')
def get(self, request, *args, **kwargs): if not self.get_object().allow_delete(): messages.error(request, _('A voucher can not be deleted if it already has been redeemed.')) return HttpResponseRedirect(self.get_success_url()) return super().get(request, *args, **kwargs)
def trial_add(request, id): # TODO: access control if request.method == 'POST': try: trial = Trial.objects.get(pk=id) except Trial.DoesNotExist: c = RequestContext( request, { 'title': 'Error | FeedDB Explorer', 'message': 'Trial with primary key %(key)r does not exist.' % { 'key': escape(id) } }) return render_to_response('explorer/error.html', c) if request.POST['bucket_id'] != u'add new bucket': bucket_id = request.POST['bucket_id'] if bucket_id == None or bucket_id == "": messages.error(request, 'No data collection specified') return HttpResponseRedirect('/explorer/trial/%s/' % id) try: bucket = Bucket.objects.get(pk=bucket_id) except Bucket.DoesNotExist: messages.error( request, 'Data collection with primary key %(key)r does not exist.' % {'key': escape(bucket_id)}) return HttpResponseRedirect('/explorer/trial/%s/' % id) #check if the user is the owner of the bucket. If not return error page if bucket.created_by.pk != request.user.pk: messages.error( request, 'Sorry, you are not allowed to change a data collection owned by another user.' ) c = RequestContext(request, {'title': 'FeedDB Explorer'}) return render_to_response('explorer/base.html', c) else: new_bucket_name = request.POST['new_bucket_name'] if new_bucket_name == None and new_bucket_name == "": messages.error(request, 'No new data collection name specified') return HttpResponseRedirect('/explorer/trial/%s/' % id) else: bucket = Bucket() if request.user.id: bucket.created_by = request.user bucket.title = new_bucket_name bucket.save() #check if bucket already contains the trial assocs = TrialInBucket.objects.filter( Q(trial__id__exact=id) & Q(bin__id__exact=bucket.id)) if len(assocs) > 0: messages.error(request, 'Trial is already included in data collection') return HttpResponseRedirect('/explorer/trial/%s/' % id) #add trials to the bucket assoc = TrialInBucket(trial=trial, bin=bucket) assoc.save() messages.success( request, 'Trial: %s has been successfully added to the data collection: %s.' % (trial, bucket)) return HttpResponseRedirect('/explorer/trial/%s/' % id)
def bucket_download(request, id): # TODO: access control message = "" bucket = get_bucket(request, id) if request.method == 'POST': try: zipfile_name = request.POST['zipfile_name'] except KeyError: zipfile_name = bucket.default_zipfile_name() if zipfile_name == "": messages.error(request, 'No zip file name selected.') c = RequestContext(request, {'title': 'FeedDB Explorer'}) return render_to_response('explorer/base.html', c) if not zipfile_name.endswith(".zip"): zipfile_name += ".zip" download_choice = request.POST['download_choice'] channel_choice = request.POST['channel_choice'] #meta_option= request.POST['meta_option'] quotechar_char = '"' #delimiter= request.POST['delimiter'] #if delimiter =="tab": # delimiter_char = '\t' #elif delimiter =="comma": # delimiter_char = ',' #else: delimiter_char = ',' #get selected fields field_selected = [] for item in request.POST.items(): if (item[1] == "on" and item[0].startswith("chk:")): field_selected.append(item[0]) message += item[0] + "\n" if (download_choice == "0" or download_choice == "2") and len(field_selected) == 0: messages.error(request, 'No fields selected.') c = RequestContext(request, {'title': 'FeedDB Explorer'}) return render_to_response('explorer/base.html', c) meta_selected = {} for field in field_selected: parts = field.split(":") if not parts[1] in meta_selected: meta_selected[parts[1]] = [] parameter = parts[1] + ":" + parts[2] meta_selected[parts[1]].append([parts[2], request.POST[parameter]]) #get selected channels channel_selected = [] channel_headers = [] for item in request.POST.items(): if (item[1] == "on" and item[0].startswith("channel:")): channel_selected.append(item[0]) message += item[0] + "\n" if (channel_choice == "1" and len(channel_selected) == 0): messages.error(request, 'No channels selected.') c = RequestContext(request, {'title': 'FeedDB Explorer'}) return render_to_response('explorer/base.html', c) channel_download = [] channel_selected.sort() trials_download = [] for ch in channel_selected: parts = ch.split(":") channel_download.append([parts[1], parts[2]]) channel_headers.append("Trial %s:Channel %s" % (parts[1], parts[2])) if not parts[1] in trials_download: trials_download.append(parts[1]) filenames = {} # create a temporary folder to store files from time import time tempdir = settings.EXPLORER_TEMPORARY_FOLDER + "/" + str( time()).replace('.', '') try: os.makedirs(tempdir) except OSError, err: messages.error( request, 'Failed to create folder for storing downloaded files.') c = RequestContext(request, {'title': 'FeedDB Explorer'}) return render_to_response('explorer/base.html', c) # # create meta data if the user has chosen to do so # if (download_choice == "0" or download_choice == "2"): #create trials mate data file and out it into the temp zip file full_filename = "%s/trials.csv" % tempdir filenames["trials.csv"] = full_filename metaWriter = UnicodeWriter(open(full_filename, "w"), delimiter=delimiter_char, doublequote='false', escapechar='\\', quotechar=quotechar_char, quoting=csv.QUOTE_MINIMAL) #output trials #output headers headers = ["Trial:ID"] for key, value in meta_selected.items(): if not key in ('Setup', 'EmgSetup', 'SonoSetup', 'Sensor', 'EmgSensor', 'SonoSensor', 'Channel', 'EmgChannel', 'SonoChannel', 'PressureChannel', 'ForceChannel', 'StrainChannel', 'KinematicsChannel', 'EventChannel'): for v in value: headers.append(v[1]) metaWriter.writerow(headers) objects = {} for trial in bucket.trials.all(): values = [trial.id] objects["Session"] = trial.session objects["Experiment"] = trial.session.experiment objects["Study"] = trial.session.experiment.study objects["Subject"] = trial.session.experiment.subject objects["Trial"] = trial for key, value in meta_selected.items(): if key in objects: for v in value: s = getattr(objects[key], v[0]) if hasattr(s, 'split'): ss = s.split('\r\n') if len(ss) > 1: s = ' '.join(ss) values.append(s) metaWriter.writerow(values) #output channels #generate channel headers headers = ["Channel:ID"] for key, value in meta_selected.items(): #generate headers meta data if key in ('Setup', 'EmgSetup', 'SonoSetup', 'Sensor', 'EmgSensor', 'SonoSensor', 'Channel', 'EmgChannel', 'SonoChannel', 'PressureChannel', 'ForceChannel', 'StrainChannel', 'KinematicsChannel', 'EventChannel'): for v in value: headers.append(v[1]) for key, value in meta_selected.items(): #generate headers for 2 meta data (specifically for crystal2 in sono data if key in ('Sensor', 'SonoSensor'): for v in value: headers.append('Sensor 2:%s' % v[1]) channel_types = [ 'strainchannel', 'forcechannel', 'pressurechannel', 'kinematicschannel' ] for trial in bucket.trials.all(): #trial_name = trial.title.replace('.', '').replace(',', '').replace(' ', '_').strip().lower() #filename = "trial_%d_%s_channels.csv" % (trial.id, trial_name) #full_filename = "%s/trial_%d_%s_channels.csv" % (tempdir, trial.id,trial_name) filename = "trial_%d_channels.csv" % trial.id full_filename = "%s/trial_%d_channels.csv" % (tempdir, trial.id) filenames[filename] = full_filename f = open(full_filename, "w") metaWriter = UnicodeWriter(f, delimiter=delimiter_char, doublequote='false', escapechar='\\', quotechar=quotechar_char, quoting=csv.QUOTE_MINIMAL) metaWriter.writerow(headers) objects = {} for lineup in trial.session.channellineup_set.all(): objects = {} ch = lineup.channel if ch == None: values = ["deadchannel"] else: objects["Channel"] = lineup.channel values = [ch.id] objects["Setup"] = ch.setup for channel_type in channel_types: if hasattr(ch, channel_type): objects["Sensor"] = getattr( ch, channel_type).sensor if hasattr(ch.setup, 'emgsetup'): objects["EmgSetup"] = ch.setup.emgsetup if hasattr(ch.setup, 'sonosetup'): objects["SonoSetup"] = ch.setup.sonosetup if hasattr(ch, 'emgchannel'): objects["EmgChannel"] = ch.emgchannel objects["Sensor"] = ch.emgchannel.sensor objects["EmgSensor"] = ch.emgchannel.sensor if hasattr(ch, 'eventchannel'): objects["EventChannel"] = ch.eventchannel if hasattr(ch, 'pressurechannel'): objects["PressureChannel"] = ch.pressurechannel if hasattr(ch, 'strainchannel'): objects["StrainChannel"] = ch.strainchannel if hasattr(ch, 'forcechannel'): objects["ForceChannel"] = ch.forcechannel if hasattr(ch, 'kinematicschannel'): objects["KinematicsChannel"] = ch.kinematicschannel if hasattr(ch, 'sonochannel'): objects["SonoChannel"] = ch.sonochannel objects["Sensor"] = ch.sonochannel.crystal1 objects["SonoSensor"] = ch.sonochannel.crystal1 if hasattr(ch, 'emgchannel'): objects["Sensor"] = ch.emgchannel.sensor for key, value in meta_selected.items(): if key in ('Setup', 'EmgSetup', 'SonoSetup', 'Sensor', 'EmgSensor', 'SonoSensor', 'Channel', 'EmgChannel', 'SonoChannel', 'PressureChannel', 'ForceChannel', 'StrainChannel', 'KinematicsChannel', 'EventChannel'): for v in value: s = '' if key in objects and objects[key] != None: s = getattr(objects[key], v[0]) if hasattr( s, 'split'): #check if s is a string ss = s.split('\r\n') if len(ss) > 1: s = ' '.join(ss) values.append(s) #output the second crystal sensor information if it is sono channel if hasattr(ch, 'sonochannel'): objects["Sensor"] = ch.sonochannel.crystal2 objects["SonoSensor"] = ch.sonochannel.crystal2 for key, value in meta_selected.items(): if key in ('Sensor', 'SonoSensor'): for v in value: s = '' if key in objects: s = getattr(objects[key], v[0]) if hasattr(s, 'split'): ss = s.split('\r\n') if len(ss) > 1: s = ' '.join(ss) values.append(s) metaWriter.writerow(values) f.close() # # put data files into the tmp zip # data_files = {} if (download_choice == "1" or download_choice == "2"): # download all trial files if channel_choice == "0": for trial in bucket.trials.all(): #check if there is a data file if (trial.data_file != None and trial.data_file != ""): filename = "trial_%d.dat" % trial.id full_filename = "%s/%s" % (settings.MEDIA_ROOT, trial.data_file) data_files[filename] = full_filename else: # download selected channels filename = "channels.dat" full_filename = "%s/channels.dat" % tempdir filenames[filename] = full_filename f = open(full_filename, "w") metaWriter = UnicodeWriter(f, delimiter=delimiter_char, doublequote='false', escapechar='\\', quotechar=quotechar_char, quoting=csv.QUOTE_MINIMAL) metaWriter.writerow(channel_headers) trial_readers = {} total_trial_number = 0 for trial in bucket.trials.all(): #check if there is a data file if (trial.data_file != None and trial.data_file != "" and str(trial.id) in trials_download): full_filename = "%s/%s" % (settings.MEDIA_ROOT, trial.data_file) csvfile = open(full_filename, "rU") dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) trial_readers[str(trial.id)] = { "reader": reader, "hasmore": True, "file": csvfile } total_trial_number += 1 rows = {} newrow = [] finished_file_number = 0 while finished_file_number < total_trial_number: rows.clear() for key in trial_readers: try: if trial_readers[key]["hasmore"]: row = trial_readers[key]["reader"].next() rows[key] = row except StopIteration: finished_file_number += 1 trial_readers[key]["hasmore"] = False trial_readers[key]["file"].close() newrow = [] for ch in channel_download: if ch[0] in rows: if int(ch[1]) > len(rows[ch[0]]): messages.error( request, "Error in channel lineup positions for trial: %s" % ch[0]) c = RequestContext( request, {'title': 'FeedDB Explorer'}) return render_to_response( 'explorer/base.html', c) newrow.append(rows[ch[0]][int(ch[1]) - 1]) else: newrow.append('') metaWriter.writerow(newrow) f.close() response = send_zipfile(request, filenames, data_files, zipfile_name) for file, full_file in filenames.items(): os.remove(full_file) os.rmdir(tempdir) return response
def salvar(request, pk=None, tab='master', output=None): from emensageriapro.efdreinf.models import STATUS_EVENTO_CADASTRADO evento_dados = {} evento_dados['status'] = STATUS_EVENTO_CADASTRADO if pk: r1000_alteracao_softhouse = get_object_or_404(r1000alteracaosoftHouse, id=pk) evento_dados = r1000_alteracao_softhouse.evento() if request.user.has_perm('r1000.can_see_r1000alteracaosoftHouse'): if pk: r1000_alteracao_softhouse_form = form_r1000_alteracao_softhouse( request.POST or None, instance=r1000_alteracao_softhouse) else: r1000_alteracao_softhouse_form = form_r1000_alteracao_softhouse( request.POST or None) if request.method == 'POST': if r1000_alteracao_softhouse_form.is_valid(): obj = r1000_alteracao_softhouse_form.save(request=request) messages.success(request, u'Salvo com sucesso!') if 'return_page' in request.session and request.session[ 'return_page'] and 'r1000-alteracao-softhouse' not in request.session[ 'return_page']: return HttpResponseRedirect(request.session['return_page']) if pk != obj.id: return redirect('r1000_alteracao_softhouse_salvar', pk=obj.id) else: messages.error(request, u'Erro ao salvar!') r1000_alteracao_softhouse_form = disabled_form_fields( r1000_alteracao_softhouse_form, request.user.has_perm('r1000.change_r1000alteracaosoftHouse')) if pk: if evento_dados['status'] != STATUS_EVENTO_CADASTRADO: r1000_alteracao_softhouse_form = disabled_form_fields( r1000_alteracao_softhouse_form, 0) if output: r1000_alteracao_softhouse_form = disabled_form_for_print( r1000_alteracao_softhouse_form) if pk: r1000_alteracao_softhouse = get_object_or_404( r1000alteracaosoftHouse, id=pk) else: r1000_alteracao_softhouse = None tabelas_secundarias = [] controle_alteracoes = Auditoria.objects.filter( identidade=pk, tabela='r1000_alteracao_softhouse').all() if not request.POST: request.session['return_page'] = request.META.get('HTTP_REFERER') context = { 'usuario': Usuarios.objects.get(user_id=request.user.id), 'pk': pk, 'output': output, 'evento_dados': evento_dados, 'controle_alteracoes': controle_alteracoes, 'r1000_alteracao_softhouse': r1000_alteracao_softhouse, 'r1000_alteracao_softhouse_form': r1000_alteracao_softhouse_form, 'modulos': [ 'r1000', ], 'paginas': [ 'r1000_alteracao_softhouse', ], 'data': datetime.datetime.now(), 'tabelas_secundarias': tabelas_secundarias, 'tab': tab, #r1000_alteracao_softhouse_salvar_custom_variaveis_context# } if output == 'pdf': from wkhtmltopdf.views import PDFTemplateResponse response = PDFTemplateResponse( request=request, template='r1000_alteracao_softhouse_salvar.html', filename="r1000_alteracao_softhouse.pdf", context=context, show_content_in_browser=True, cmd_options={ 'margin-top': 10, 'margin-bottom': 10, 'margin-right': 10, 'margin-left': 10, 'zoom': 1, 'dpi': 72, 'orientation': 'Landscape', "viewport-size": "1366 x 513", 'javascript-delay': 1000, 'footer-center': '[page]/[topage]', "no-stop-slow-scripts": True }, ) return response elif output == 'xls': from django.shortcuts import render_to_response response = render_to_response( 'r1000_alteracao_softhouse_salvar.html', context) filename = "r1000_alteracao_softhouse.xls" response[ 'Content-Disposition'] = 'attachment; filename=' + filename response[ 'Content-Type'] = 'application/vnd.ms-excel; charset=UTF-8' return response else: return render(request, 'r1000_alteracao_softhouse_salvar.html', context) else: context = { 'usuario': Usuarios.objects.get(user_id=request.user.id), 'pk': pk, 'output': output, 'tab': tab, 'modulos': [ 'r1000', ], 'paginas': [ 'r1000_alteracao_softhouse', ], 'data': datetime.datetime.now(), } return render(request, 'permissao_negada.html', context)
def salvar(request, hash): db_slug = 'default' try: usuario_id = request.user.id dict_hash = get_hash_url( hash ) r2070_pgtopj_despprocjud_id = int(dict_hash['id']) if 'tab' not in dict_hash.keys(): dict_hash['tab'] = '' for_print = int(dict_hash['print']) except: usuario_id = False return redirect('login') usuario = get_object_or_404(Usuarios.objects.using( db_slug ), excluido = False, id = usuario_id) pagina = ConfigPaginas.objects.using( db_slug ).get(excluido = False, endereco='r2070_pgtopj_despprocjud') permissao = ConfigPermissoes.objects.using( db_slug ).get(excluido = False, config_paginas=pagina, config_perfis=usuario.config_perfis) if r2070_pgtopj_despprocjud_id: r2070_pgtopj_despprocjud = get_object_or_404(r2070pgtoPJdespProcJud.objects.using( db_slug ), excluido = False, id = r2070_pgtopj_despprocjud_id) dict_permissoes = json_to_dict(usuario.config_perfis.permissoes) paginas_permitidas_lista = usuario.config_perfis.paginas_permitidas modulos_permitidos_lista = usuario.config_perfis.modulos_permitidos dados_evento = {} dados_evento['status'] = 0 if r2070_pgtopj_despprocjud_id: dados_evento = r2070_pgtopj_despprocjud.evento() if dados_evento['status'] != 0: dict_permissoes['r2070_pgtopj_despprocjud_apagar'] = 0 dict_permissoes['r2070_pgtopj_despprocjud_editar'] = 0 if permissao.permite_visualizar: mensagem = None if r2070_pgtopj_despprocjud_id: r2070_pgtopj_despprocjud_form = form_r2070_pgtopj_despprocjud(request.POST or None, instance = r2070_pgtopj_despprocjud, slug = db_slug) else: r2070_pgtopj_despprocjud_form = form_r2070_pgtopj_despprocjud(request.POST or None, slug = db_slug, initial={}) if request.method == 'POST': if r2070_pgtopj_despprocjud_form.is_valid(): dados = r2070_pgtopj_despprocjud_form.cleaned_data import json from django.forms.models import model_to_dict if r2070_pgtopj_despprocjud_id: if dados_evento['status'] == 0: dados['modificado_por_id'] = usuario_id dados['modificado_em'] = datetime.datetime.now() #r2070_pgtopj_despprocjud_campos_multiple_passo1 r2070pgtoPJdespProcJud.objects.using(db_slug).filter(id=r2070_pgtopj_despprocjud_id).update(**dados) obj = r2070pgtoPJdespProcJud.objects.using(db_slug).get(id=r2070_pgtopj_despprocjud_id) #r2070_pgtopj_despprocjud_editar_custom #r2070_pgtopj_despprocjud_campos_multiple_passo2 messages.success(request, 'Alterado com sucesso!') gravar_auditoria(json.dumps(model_to_dict(r2070_pgtopj_despprocjud), indent=4, sort_keys=True, default=str), json.dumps(model_to_dict(obj), indent=4, sort_keys=True, default=str), 'r2070_pgtopj_despprocjud', r2070_pgtopj_despprocjud_id, usuario_id, 2) else: messages.error(request, 'Somente é possível alterar eventos com status "Cadastrado"!') else: dados['criado_por_id'] = usuario_id dados['criado_em'] = datetime.datetime.now() dados['excluido'] = False #r2070_pgtopj_despprocjud_cadastrar_campos_multiple_passo1 obj = r2070pgtoPJdespProcJud(**dados) obj.save(using = db_slug) #r2070_pgtopj_despprocjud_cadastrar_custom #r2070_pgtopj_despprocjud_cadastrar_campos_multiple_passo2 messages.success(request, 'Cadastrado com sucesso!') gravar_auditoria('{}', json.dumps(model_to_dict(obj), indent=4, sort_keys=True, default=str), 'r2070_pgtopj_despprocjud', obj.id, usuario_id, 1) if request.session['retorno_pagina'] not in ('r2070_pgtopj_despprocjud_apagar', 'r2070_pgtopj_despprocjud_salvar', 'r2070_pgtopj_despprocjud'): return redirect(request.session['retorno_pagina'], hash=request.session['retorno_hash']) if r2070_pgtopj_despprocjud_id != obj.id: url_hash = base64.urlsafe_b64encode( '{"print": "0", "id": "%s"}' % (obj.id) ) return redirect('r2070_pgtopj_despprocjud_salvar', hash=url_hash) else: messages.error(request, 'Erro ao salvar!') r2070_pgtopj_despprocjud_form = disabled_form_fields(r2070_pgtopj_despprocjud_form, permissao.permite_editar) if r2070_pgtopj_despprocjud_id: if dados_evento['status'] != 0: r2070_pgtopj_despprocjud_form = disabled_form_fields(r2070_pgtopj_despprocjud_form, 0) #r2070_pgtopj_despprocjud_campos_multiple_passo3 for field in r2070_pgtopj_despprocjud_form.fields.keys(): r2070_pgtopj_despprocjud_form.fields[field].widget.attrs['ng-model'] = 'r2070_pgtopj_despprocjud_'+field if int(dict_hash['print']): r2070_pgtopj_despprocjud_form = disabled_form_for_print(r2070_pgtopj_despprocjud_form) r2070_pgtopj_ideadvogado_form = None r2070_pgtopj_ideadvogado_lista = None if r2070_pgtopj_despprocjud_id: r2070_pgtopj_despprocjud = get_object_or_404(r2070pgtoPJdespProcJud.objects.using( db_slug ), excluido = False, id = r2070_pgtopj_despprocjud_id) r2070_pgtopj_ideadvogado_form = form_r2070_pgtopj_ideadvogado(initial={ 'r2070_pgtopj_despprocjud': r2070_pgtopj_despprocjud }, slug=db_slug) r2070_pgtopj_ideadvogado_form.fields['r2070_pgtopj_despprocjud'].widget.attrs['readonly'] = True r2070_pgtopj_ideadvogado_lista = r2070pgtoPJideAdvogado.objects.using( db_slug ).filter(excluido = False, r2070_pgtopj_despprocjud_id=r2070_pgtopj_despprocjud.id).all() else: r2070_pgtopj_despprocjud = None #r2070_pgtopj_despprocjud_salvar_custom_variaveis# tabelas_secundarias = [] #[FUNCOES_ESPECIAIS_SALVAR] if dict_hash['tab'] or 'r2070_pgtopj_despprocjud' in request.session['retorno_pagina']: request.session["retorno_hash"] = hash request.session["retorno_pagina"] = 'r2070_pgtopj_despprocjud_salvar' controle_alteracoes = Auditoria.objects.using( db_slug ).filter(identidade=r2070_pgtopj_despprocjud_id, tabela='r2070_pgtopj_despprocjud').all() context = { 'ocorrencias': dados_evento['ocorrencias'], 'validacao_precedencia': dados_evento['validacao_precedencia'], 'validacoes': dados_evento['validacoes'], 'status': dados_evento['status'], 'controle_alteracoes': controle_alteracoes, 'r2070_pgtopj_despprocjud': r2070_pgtopj_despprocjud, 'r2070_pgtopj_despprocjud_form': r2070_pgtopj_despprocjud_form, 'mensagem': mensagem, 'r2070_pgtopj_despprocjud_id': int(r2070_pgtopj_despprocjud_id), 'usuario': usuario, 'hash': hash, 'r2070_pgtopj_ideadvogado_form': r2070_pgtopj_ideadvogado_form, 'r2070_pgtopj_ideadvogado_lista': r2070_pgtopj_ideadvogado_lista, 'modulos_permitidos_lista': modulos_permitidos_lista, 'paginas_permitidas_lista': paginas_permitidas_lista, 'permissao': permissao, 'data': datetime.datetime.now(), 'pagina': pagina, 'dict_permissoes': dict_permissoes, 'for_print': int(dict_hash['print']), 'tabelas_secundarias': tabelas_secundarias, 'tab': dict_hash['tab'], #r2070_pgtopj_despprocjud_salvar_custom_variaveis_context# } if for_print in (0,1 ): return render(request, 'r2070_pgtopj_despprocjud_salvar.html', context) elif for_print == 2: from wkhtmltopdf.views import PDFTemplateResponse response = PDFTemplateResponse( request=request, template='r2070_pgtopj_despprocjud_salvar.html', filename="r2070_pgtopj_despprocjud.pdf", context=context, show_content_in_browser=True, cmd_options={'margin-top': 10, 'margin-bottom': 10, 'margin-right': 10, 'margin-left': 10, 'zoom': 1, 'dpi': 72, 'orientation': 'Landscape', "viewport-size": "1366 x 513", 'javascript-delay': 1000, 'footer-center': '[page]/[topage]', "no-stop-slow-scripts": True}, ) return response elif for_print == 3: from django.shortcuts import render_to_response response = render_to_response('r2070_pgtopj_despprocjud_salvar.html', context) filename = "r2070_pgtopj_despprocjud.xls" response['Content-Disposition'] = 'attachment; filename=' + filename response['Content-Type'] = 'application/vnd.ms-excel; charset=UTF-8' return response else: context = { 'usuario': usuario, 'modulos_permitidos_lista': modulos_permitidos_lista, 'paginas_permitidas_lista': paginas_permitidas_lista, 'permissao': permissao, 'data': datetime.datetime.now(), 'pagina': pagina, 'dict_permissoes': dict_permissoes, } return render(request, 'permissao_negada.html', context)
def checkout(request): """ A view to ensure that payment information is being handled by stripe correctly, so that the user will be able to purchase items. The view renders the html page and pass in the forms and contents of the cart. """ if request.method == "POST": order_form = NewOrderForm(request.POST) payment_form = MakePaymentForm(request.POST) # # if the order form and the payment form is valid, # filled out correctly, then the order form will be saved as order. if order_form.is_valid() and payment_form.is_valid(): order = order_form.save(commit=False) order.date = timezone.now() order.user = request.user order.save() # get the information from the cart from the current session, # about what is being purchased. cart = request.session.get('cart', {}) total = 0 for id, quantity in cart.items(): product = get_object_or_404(Product, pk=id) total += quantity * product.price order_item = OrderItem(order=order, product=product, quantity=quantity) order_item.save() # a try except that will create a customer charge, using Stripe's in-built API. try: customer = stripe.Charge.create( amount=int(total * 100), currency="EUR", description=request.user.email, card=payment_form.cleaned_data['stripe_id']) # If the card is being declined. except stripe.error.CardError: messages.error(request, "Your card was declined!") # if the customer have paid, request the cart from the current session. if customer.paid: messages.error(request, "You have successfully paid") request.session['cart'] = {} return redirect(reverse('products')) # if the user have not paid. else: messages.error( request, "We were unable to take your payment at this time") # if any payment form errors occurs. else: print(payment_form.errors) messages.error(request, "We were unable to take a payment from this card") # return a payment form and an order form as blank. else: payment_form = MakePaymentForm() order_form = NewOrderForm() # return the checkout html with an order form, a payment form, and a publishable key for Stripe, # available on the HTML page when the user clicks on checkout. return render( request, "checkout.html", { "order_form": order_form, "payment_form": payment_form, "publishable": settings.STRIPE_PUBLISHABLE })
def abrir_evento_para_edicao(request, pk): from emensageriapro.settings import BASE_DIR from emensageriapro.mensageiro.functions.funcoes import gravar_nome_arquivo if request.user.has_perm('esocial.can_open_s1260evtComProd'): s1260_evtcomprod = get_object_or_404(s1260evtComProd, id=pk) status_list = [ STATUS_EVENTO_CADASTRADO, STATUS_EVENTO_IMPORTADO, STATUS_EVENTO_DUPLICADO, STATUS_EVENTO_GERADO, STATUS_EVENTO_GERADO_ERRO, STATUS_EVENTO_ASSINADO, STATUS_EVENTO_ASSINADO_ERRO, STATUS_EVENTO_VALIDADO, STATUS_EVENTO_VALIDADO_ERRO, STATUS_EVENTO_AGUARD_PRECEDENCIA, STATUS_EVENTO_AGUARD_ENVIO, STATUS_EVENTO_ENVIADO_ERRO ] if s1260_evtcomprod.status in status_list: s1260evtComProd.objects.filter(id=pk).update( status=STATUS_EVENTO_CADASTRADO, arquivo_original=0) arquivo = '/arquivos/Eventos/s1260_evtcomprod/%s.xml' % (s1260_evtcomprod.identidade) if os.path.exists(BASE_DIR + arquivo): data_hora_atual = str(datetime.now()).replace(':','_').replace(' ','_').replace('.','_') dad = (BASE_DIR, s1260_evtcomprod.identidade, BASE_DIR, s1260_evtcomprod.identidade, data_hora_atual) os.system('mv %s/arquivos/Eventos/s1260_evtcomprod/%s.xml %s/arquivos/Eventos/s1260_evtcomprod/%s_backup_%s.xml' % dad) gravar_nome_arquivo('/arquivos/Eventos/s1260_evtcomprod/%s_backup_%s.xml' % (s1260_evtcomprod.identidade, data_hora_atual), 1) messages.success(request, 'Evento aberto para edição!') request.user.id = request.user.id gravar_auditoria(u'{}', u'{"funcao": "Evento aberto para edição"}', 's1260_evtcomprod', pk, request.user.id, 2) else: messages.error(request, u''' Não foi possível abrir o evento para edição! Somente é possível abrir eventos com os seguintes status: "Cadastrado", "Importado", "Validado", "Duplicado", "Erro na validação", "XML Assinado" ou "XML Gerado" ou com o status "Enviado com sucesso" e os seguintes códigos de resposta do servidor: "401 - Lote Incorreto - Erro preenchimento" ou "402 - Lote Incorreto - schema Inválido"!''') else: messages.error(request, u'''Você não possui permissão para abrir evento para edição. Entre em contato com o administrador do sistema!''') return redirect('s1260_evtcomprod_salvar', pk=pk)
def wrap(request, *args, **kwargs): # try authenticating the user if request.session.get('uname', None) == None: messages.error(request, "Must login to lazychef.") return HttpResponseRedirect(reverse('login')) return f(request, *args, **kwargs)
def schedule_activity_view(request): if request.method == "POST": formset = ScheduledActivityFormset(request.POST) if formset.is_valid(): for form in formset: block = form.cleaned_data["block"] activity = form.cleaned_data["activity"] # Save changes to cancelled activities and scheduled activities cancelled = (EighthScheduledActivity.objects.filter( block=block, activity=activity, cancelled=True).exists()) instance = None if form["scheduled"].value() or cancelled: instance, created = ( EighthScheduledActivity.objects.get_or_create( block=block, activity=activity)) invalidate_obj(instance) invalidate_obj(block) invalidate_obj(activity) else: schact = EighthScheduledActivity.objects.filter( block=block, activity=activity) logger.debug(block) logger.debug(activity) logger.debug(schact) # Instead of deleting and messing up attendance, # cancel the scheduled activity if it is unscheduled. # If the scheduled activity needs to be completely deleted, # the "Unschedule" box can be checked after it has been cancelled. # If a both blocks activity, unschedule the other # scheduled activities of it on the same day. if schact: if activity.both_blocks: other_act = schact[0].get_both_blocks_sibling() logger.debug("other_act: {}".format(other_act)) if other_act: other_act.cancelled = True other_act.save() invalidate_obj(other_act) else: schact.update(cancelled=True) for s in schact: invalidate_obj(s) instance = schact[0] cancelled = True if instance: fields = [ "rooms", "capacity", "sponsors", "title", "special", "administrative", "restricted", "sticky", "both_blocks", "comments", "admin_comments" ] if "rooms" in form.cleaned_data: for o in form.cleaned_data["rooms"]: invalidate_obj(o) if "sponsors" in form.cleaned_data: for o in form.cleaned_data["sponsors"]: invalidate_obj(o) for field_name in fields: obj = form.cleaned_data[field_name] logger.debug("{} {}".format(field_name, obj)) # Properly handle ManyToMany relations in django 1.10+ if isinstance(getattr(instance, field_name), Manager): getattr(instance, field_name).set(obj) else: setattr(instance, field_name, obj) if field_name in ["rooms", "sponsors"]: for o in obj: invalidate_obj(o) if form["scheduled"].value() or cancelled: # Uncancel if this activity/block pairing was already # created and cancelled instance.cancelled = not form["scheduled"].value() # If an activity has already been cancelled and the # unschedule checkbox has been checked, delete the # EighthScheduledActivity instance. If there are students # in the activity then error out. if form["unschedule"].value() and instance.cancelled: name = "{}".format(instance) count = instance.eighthsignup_set.count() logger.debug("Unschedule {} - signups {}".format( name, count)) bb_ok = True sibling = False if activity.both_blocks: sibling = instance.get_both_blocks_sibling() if sibling: if not sibling.eighthsignup_set.count() == 0: bb_ok = False if count == 0 and bb_ok: instance.delete() if sibling: sibling.delete() messages.success(request, "Unscheduled {}".format(name)) continue # don't run instance.save() elif count == 1: messages.error( request, "Did not unschedule {} because there is {} student signed up." .format(name, count)) else: messages.error( request, "Did not unschedule {} because there are {} students signed up." .format(name, count)) instance.save() logger.debug(instance) messages.success(request, "Successfully updated schedule.") # Force reload everything from the database to reset # forms that weren't saved return redirect(request.get_full_path()) else: messages.error(request, "Error updating schedule.") activities = EighthActivity.undeleted_objects.order_by("name") activity_id = request.GET.get("activity", None) activity = None if activity_id is not None and len(activity_id) > 0: try: activity = EighthActivity.undeleted_objects.get(id=activity_id) except (EighthActivity.DoesNotExist, ValueError): pass all_sponsors = {s["id"]: s for s in EighthSponsor.objects.values()} all_rooms = {r["id"]: r for r in EighthRoom.objects.values()} for sid, sponsor in all_sponsors.items(): if sponsor["show_full_name"]: all_sponsors[sid]["full_name"] = sponsor[ "last_name"] + ", " + sponsor["first_name"] else: all_sponsors[sid]["full_name"] = sponsor["last_name"] for rid, room in all_rooms.items(): all_rooms[rid]["description"] = room["name"] + " (" + str( room["capacity"]) + ")" all_signups = {} all_default_capacities = {} context = { "activities": activities, "activity": activity, "sponsors": all_sponsors, "all_signups": all_signups, "rooms": all_rooms, "sponsors_json": safe_json(all_sponsors), "rooms_json": safe_json(all_rooms) } if activity is not None: start_date = get_start_date(request) # end_date = start_date + timedelta(days=60) blocks = EighthBlock.objects.filter(date__gte=start_date) # , date__lte=end_date) initial_formset_data = [] sched_act_queryset = (EighthScheduledActivity.objects.filter( activity=activity).select_related("block").prefetch_related( "rooms", "sponsors", "members")) all_sched_acts = {sa.block.id: sa for sa in sched_act_queryset} for block in blocks: initial_form_data = {"block": block, "activity": activity} try: sched_act = all_sched_acts[block.id] all_signups[block.id] = sched_act.members.count() all_default_capacities[ block.id] = sched_act.get_true_capacity() logger.debug(sched_act) initial_form_data.update({ "rooms": sched_act.rooms.all(), "capacity": sched_act.capacity, "sponsors": sched_act.sponsors.all(), "title": sched_act.title, "special": sched_act.special, "administrative": sched_act.administrative, "restricted": sched_act.restricted, "sticky": sched_act.sticky, "both_blocks": sched_act.both_blocks, "comments": sched_act.comments, "admin_comments": sched_act.admin_comments, "scheduled": not sched_act.cancelled, "cancelled": sched_act.cancelled }) except KeyError: all_signups[block.id] = 0 all_default_capacities[block.id] = activity.capacity() pass initial_formset_data.append(initial_form_data) if request.method != "POST": # There must be an error in the form if this is reached formset = ScheduledActivityFormset(initial=initial_formset_data) context["formset"] = formset context["rows"] = list(zip(blocks, formset)) context["default_rooms"] = activity.rooms.all() context["default_sponsors"] = activity.sponsors.all() context["default_capacities"] = all_default_capacities context["admin_page_title"] = "Schedule an Activity" return render(request, "eighth/admin/schedule_activity.html", context)
def form_valid(self, form): qs = Order.objects.filter(event=self.request.event) statusq = Q(status__in=form.cleaned_data['sendto']) if 'overdue' in form.cleaned_data['sendto']: statusq |= Q(status=Order.STATUS_PENDING, expires__lt=now()) if 'pa' in form.cleaned_data['sendto']: statusq |= Q(status=Order.STATUS_PENDING, require_approval=True) if 'na' in form.cleaned_data['sendto']: statusq |= Q(status=Order.STATUS_PENDING, require_approval=False) orders = qs.filter(statusq) opq = OrderPosition.objects.filter( order=OuterRef('pk'), canceled=False, item_id__in=[i.pk for i in form.cleaned_data.get('items')], ) if form.cleaned_data.get('filter_checkins'): ql = [] if form.cleaned_data.get('not_checked_in'): opq = opq.alias( any_checkins=Exists( Checkin.all.filter( position_id=OuterRef('pk'), successful=True ) ) ) ql.append(Q(any_checkins=False)) if form.cleaned_data.get('checkin_lists'): opq = opq.alias( matching_checkins=Exists( Checkin.all.filter( position_id=OuterRef('pk'), list_id__in=[i.pk for i in form.cleaned_data.get('checkin_lists', [])], successful=True ) ) ) ql.append(Q(matching_checkins=True)) if len(ql) == 2: opq = opq.filter(ql[0] | ql[1]) elif ql: opq = opq.filter(ql[0]) else: opq = opq.none() if form.cleaned_data.get('subevent'): opq = opq.filter(subevent=form.cleaned_data.get('subevent')) if form.cleaned_data.get('subevents_from'): opq = opq.filter(subevent__date_from__gte=form.cleaned_data.get('subevents_from')) if form.cleaned_data.get('subevents_to'): opq = opq.filter(subevent__date_from__lt=form.cleaned_data.get('subevents_to')) if form.cleaned_data.get('created_from'): opq = opq.filter(order__datetime__gte=form.cleaned_data.get('created_from')) if form.cleaned_data.get('created_to'): opq = opq.filter(order__datetime__lt=form.cleaned_data.get('created_to')) orders = orders.annotate(match_pos=Exists(opq)).filter(match_pos=True).distinct() self.output = {} if not orders: messages.error(self.request, _('There are no orders matching this selection.')) return self.get(self.request, *self.args, **self.kwargs) if self.request.POST.get("action") == "preview": for l in self.request.event.settings.locales: with language(l, self.request.event.settings.region): context_dict = TolerantDict() for k, v in get_available_placeholders(self.request.event, ['event', 'order', 'position_or_address']).items(): context_dict[k] = '<span class="placeholder" title="{}">{}</span>'.format( _('This value will be replaced based on dynamic parameters.'), v.render_sample(self.request.event) ) subject = bleach.clean(form.cleaned_data['subject'].localize(l), tags=[]) preview_subject = subject.format_map(context_dict) message = form.cleaned_data['message'].localize(l) preview_text = markdown_compile_email(message.format_map(context_dict)) self.output[l] = { 'subject': _('Subject: {subject}').format(subject=preview_subject), 'html': preview_text, } return self.get(self.request, *self.args, **self.kwargs) kwargs = { 'recipients': form.cleaned_data['recipients'], 'event': self.request.event.pk, 'user': self.request.user.pk, 'subject': form.cleaned_data['subject'].data, 'message': form.cleaned_data['message'].data, 'orders': [o.pk for o in orders], 'items': [i.pk for i in form.cleaned_data.get('items')], 'not_checked_in': form.cleaned_data.get('not_checked_in'), 'checkin_lists': [i.pk for i in form.cleaned_data.get('checkin_lists')], 'filter_checkins': form.cleaned_data.get('filter_checkins'), } if form.cleaned_data.get('attachment') is not None: kwargs['attachments'] = [form.cleaned_data['attachment'].id] send_mails.apply_async( kwargs=kwargs ) self.request.event.log_action('pretix.plugins.sendmail.sent', user=self.request.user, data=dict(form.cleaned_data)) messages.success(self.request, _('Your message has been queued and will be sent to the contact addresses of %d ' 'orders in the next few minutes.') % len(orders)) return redirect( 'plugins:sendmail:send', event=self.request.event.slug, organizer=self.request.event.organizer.slug )
def uploadcsv(request): data = {} if "GET" == request.method: return render(request, "cleancsv/upload_csv.html", data) try: csv_file = request.FILES["csv_file"] if not csv_file.name.endswith('.csv'): messages.error(request, 'File is not CSV type', extra_tags='alert') return HttpResponseRedirect(reverse("cleancsv:upload_csv")) # if file is too large, return if csv_file.multiple_chunks(chunk_size=5242880): messages.error( request, "Uploaded file is too big. Make sure file is less than 5 MB. (%.2f MB)." % (csv_file.size / (1000 * 1000), ), extra_tags='alert') return HttpResponseRedirect(reverse("cleancsv:upload_csv")) """ - Make rename/match thing a function? """ start_time = time.time() # point to file location. df = pd.read_csv(csv_file) df.columns = [i.lower().replace(' ', '_') for i in df.columns] # lower case and replace spaces df.index += 2 # so when it says "check these lines" the numbers match with csv # removes empty rows then empty columns df = df.dropna(how='all') df = df.dropna(axis=1, how='all') # might put into a functions # starts at -1 so it doesn't skip first entry in list i = -1 for rename_col in rename_list: i += 1 # stops index error if i < 28: # get i nested list in match_list (the list with all possible column names) and assign it to current_list current_list = match_list[i] # create empty list of tried column header list from current_list tried_colname = [] # for each possible column name in current_list for try_col in current_list: # if the rename_col not in df if rename_col not in df.columns: try: # try to find try_col in df and rename it to what rename_col is df.rename(columns={try_col: rename_col}, inplace=True) # add try_col to tried_col list so we don't try it again tried_colname.append(try_col) # if the rename does not add rename_col to df and i is less than 4 then do below # I have i < 4 because the first 4 columns are needed to merger so they go through an additional matching attempt # and the others are just so the headers are automatically matched when uploaded if rename_col not in df.columns and i < 4: # if the number of items we tried equals the number of items in the list if len(tried_colname) == len(current_list): try: # try to find the first column in df that is similar to rename_col and rename it to rename_col df = df.rename( columns={ df.filter(like=rename_col).columns[0]: rename_col }) print('Filter match', rename_col) continue # if try didn't work then throw exception since those 4 columns are needed for merger except Exception as e: print( f"Unable to match a column the same as or close to {rename_col}. - Exception: {e}" ) break else: continue # this breaks so it doesn't continue trying to check when it has already been match elif rename_col in df.columns: print(f"Matched {rename_col} with {try_col}.") break else: print( f"Unable to match {rename_col} with any columns." ) break except Exception as e: print(f"How did you get here!? - Exception: {e}") break else: break # just to be safe # not needed since above raises an exception if any of the below columns aren't in df or matched this is just a safety check since it is quick if 'first_name' not in df.columns: raise KeyError('CSV file does not have a first_name column.') if 'last_name' not in df.columns: raise KeyError('CSV file does not have a last_name column.') if 'email' not in df.columns: raise KeyError('CSV file does not have a email column.') if 'phone' not in df.columns: raise KeyError('CSV file does not have a phone column.') if 'address' not in df.columns: # if all of these things are columns in the df then combine them under the column name 'address' if set([ 'house_number', 'dir_prefix', 'street', 'street_type', 'dir_suffix', 'suite', 'po_box' ]).issubset(df.columns): df['address'] = ( df['house_number'].astype(str).fillna('') + ' ' + df['dir_prefix'].astype(str).fillna('') + ' ' + df['street'].astype(str).fillna('') + ' ' + df['street_type'].astype(str).fillna('') + ' ' + df['dir_suffix'].astype(str).fillna('') + ' ' + df['suite'].astype(str).fillna('') + ' ' + df['po_box'].astype(str).fillna('')) elif set([ 'house_number', 'direction_prefix', 'street', 'street_designator', 'suite_no' ]).issubset(df.columns): df['address'] = ( df['house_number'].astype(str).fillna('') + ' ' + df['direction_prefix'].astype(str).fillna('') + ' ' + df['street'].astype(str).fillna('') + ' ' + df['street_designator'].astype(str).fillna('') + ' ' + df['suite_no'].astype(str).fillna('')) if 'assigned_agent' not in df.columns: # if these columns in the df then combine them under the column name 'assigned_agent' if set(['member_first_name', 'member_last_name']).issubset(df.columns): df['assigned_agent'] = df['member_first_name'].fillna( '') + ' ' + df['member_last_name'].fillna('') if 'second_contact_name' not in df.columns: # if all of these things are columns in the df then combine them under the column name 'second_contact_name' if set([ 'secondary_title', 'secondary_first_name', 'secondary_nickname', 'secondary_last_name' ]).issubset(df.columns): df['second_contact_name'] = ( df['secondary_title'].fillna('') + ' ' + df['secondary_first_name'].fillna('') + ' ' + df['secondary_nickname'].fillna('') + df['secondary_last_name'].fillna('')) elif set(['first_name_2', 'last_name_2']).issubset(df.columns): df['second_contact_name'] = df['first_name_2'].fillna( '') + ' ' + df['last_name_2'].fillna('') # assign list of df cols to 'cols' for when we move columns and merge rows cols = list(df) """ email_list = df['email'] email_counts = email_list.value_counts() duplicate_emails = list(email_counts[email_counts > 1].index) print(f'Check these emails for duplicates: {duplicate_emails}') phone_list = df['phone'] phone_list = phone_list.replace('[^0-9]+', '', regex=True) # remove special characters phone_len = phone_list.str.len() phone_bad = list(phone_len[(phone_len < 8) | (phone_len > 15)].index) print(f'Check these lines for an incomplete phone number: {phone_bad}') """ # reorder columns to when they are merged it doesn't have double emails or phone numbers which bypasses the validation cols.insert(0, cols.pop(cols.index('first_name'))) cols.insert(1, cols.pop(cols.index('last_name'))) cols.insert(2, cols.pop(cols.index('email'))) cols.insert(3, cols.pop(cols.index('phone'))) df = df.reindex(columns=cols) if (df['email'].str.contains(',')).any(): df['secondary_email'] = None df.columns = df.columns.fillna('secondary_email') # splits email list so that everything before comma is put in email and the rest into secondary_email df['email'], df['secondary_email'] = df['email'].str.split(',', 1).str if 'second_contact_email' in df.columns: # this handles in case they do have the 'second_contact_email' column # Merges secondary_email into the 'second_contact_email' column df['second_contact_email'] = df['second_contact_email'].fillna( '') + ', ' + df['secondary_email'].fillna('') # this is to just clean up column (i.e. remove leadning what space and random extra commas from merge) df['second_contact_email'] = df[ 'second_contact_email'].replace('((, )$|[,]$)|(^\s)', '', regex=True) df = df.iloc[:, : -1] # drops last column so there isn't double 'second_contact_email' df.rename(columns={'secondary_email': 'second_contact_email'}, inplace=True) else: pass # if there is a bad email then do stuff. its here to help with speed (not an issue but who knows) and to stop adding a second_contact_email when its not needed if ~df.email.str.contains( r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$').all(): if 'second_contact_email' in df.columns: # validate email and move bad ones df['temp_second_contact_email'] = df[~df['email'].str.contains( pat=r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', case=False, na=False)]['email'] df['email'] = df[df['email'].str.contains( pat=r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', case=False, na=False)]['email'] # merges columns so original second_contact_email doesn't get replaced by temp_second_contact_email df['second_contact_email'] = df['second_contact_email'].fillna( '') + ', ' + df['temp_second_contact_email'].fillna('') del df['temp_second_contact_email'] # this is to just clean up column (i.e. remove leadning what space and random extra commas from merge) df['second_contact_email'] = df[ 'second_contact_email'].replace('((, )$|[,]$)|(^\s)', '', regex=True) # definitely not needed but one case bothered me so I added it df['second_contact_email'] = df[ 'second_contact_email'].replace('( )', ' ', regex=True) else: if 'second_contact_email' not in df.columns: df['second_contact_email'] = '' # validate email and move bad ones df['temp_second_contact_email'] = df[ ~df['email'].str.contains( pat= r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', case=False, na=False)]['email'] df['email'] = df[df['email'].str.contains( pat=r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', case=False, na=False)]['email'] # merges columns so original second_contact_email doesn't get replaced by temp_second_contact_email df['second_contact_email'] = df[ 'second_contact_email'].fillna('') + ', ' + df[ 'temp_second_contact_email'].fillna('') del df['temp_second_contact_email'] # this is to just clean up column (i.e. remove leadning what space and random extra commas from merge) df['second_contact_email'] = df[ 'second_contact_email'].replace('((, )$|[,]$)|(^\s)', '', regex=True) # definitely not needed but one case bothered me so I added it df['second_contact_email'] = df[ 'second_contact_email'].replace('( )', ' ', regex=True) # needed for below merger. Gets column headers get_col_headers = str(list(df)) # gets rid of [''] around header names col_headers = eval(get_col_headers) # searches column named email and drops duplicates but keeps the first one and merges data # https://github.com/khalido/notebooks/blob/master/pandas-dealing-with-dupes.ipynb df["first_dupe"] = df.duplicated( "email", keep=False) & ~df.duplicated("email", keep="first") def combine_rows(row, key="email", cols_to_combine=col_headers[3:]): # takes in a row, looks at the key column if its the first dupe, combines the data in cols_to_combine with the other rows with same key # needs a dataframe with a bool column first_dupe with True if the row is the first dupe if row['first_dupe'] is True: # making a df of dupes item dupes = df[df[key] == row[key]] # skipping the first row, since thats our first_dupe for i, dupe_row in dupes.iloc[1:].iterrows(): for col in cols_to_combine: dupe_row[col] = str(dupe_row[col]) row[col] = str(row[col]) row[col] += ", " + dupe_row[col] # make sure first_dupe doesn't get processed again row.first_dupe = False return row df = df.apply(combine_rows, axis=1, result_type=None) # drops dup emails but keep first instance since everything should have been merged into that but ignores cells that are empty because # before it would just delete all rows with an empty email cell but the first one..... df = df[df['email'].isnull() | ~df[df['email'].notnull()]. duplicated(subset='email', keep='first')] df.groupby('email').agg(lambda x: ", ".join(x)).reset_index() del df['first_dupe'] if df.phone.astype(str).str.contains(',').any(): if 'second_contact_phone' in df.columns: # split phone numbers by comma and add to second_contact_phone df['phone'], df['temp_phone'] = df['phone'].str.split(',', 1).str df['second_contact_phone'] = df['second_contact_phone'].astype( str).fillna('') + ', ' + df['temp_phone'].astype( str).fillna('') del df['temp_phone'] if 'second_contact_phone' not in df.columns: df['second_contact_phone'] = '' df['phone'], df['temp_phone'] = df['phone'].str.split(',', 1).str df['second_contact_phone'] = df['second_contact_phone'].astype( str).fillna('') + ', ' + df['temp_phone'].astype( str).fillna('') del df['temp_phone'] # only keep numbers in phone column df['phone'] = df['phone'].replace('[^0-9]+', '', regex=True) # if there is a bad phone then do stuff. its here to help with speed (not an issue but who knows) and to stop adding a second_contact_phone when its not needed if df.phone.astype(str).str.contains( '^(?:(?!^.{,7}$|^.{16,}$).)*$').any(): if 'second_contact_phone' in df.columns: # moves phone numbers less than 8 and greater than 15 digits then removes them from phone df['temp_second_contact_phone'] = df[~df['phone'].astype( str).str.contains(pat=r'^(?:(?!^.{,7}$|^.{16,}$).)*$', case=False, na=False)]['phone'] df['phone'] = df[df['phone'].astype(str).str.contains( pat=r'^(?:(?!^.{,7}$|^.{16,}$).)*$', case=False, na=False)]['phone'] # merges columns so original second_contact_email doesn't get replaced by temp_second_contact_email df['second_contact_phone'] = df['second_contact_phone'].astype( str).fillna('') + ', ' + df[ 'temp_second_contact_phone'].astype(str).fillna('') del df['temp_second_contact_phone'] # this is to just clean up column (i.e. remove leadning what space, random extra commas from merge, and random .0) df['second_contact_phone'] = df[ 'second_contact_phone'].replace('((, )$|[,]$|(^\s)|(\.0))', '', regex=True) # definitely not needed but one case bothered me so I added it df['second_contact_phone'] = df[ 'second_contact_phone'].replace('( )', ' ', regex=True) else: if 'second_contact_phone' not in df.columns: df['second_contact_phone'] = '' # moves phone numbers less than 8 and greater than 15 digits then removes them from phone df['temp_second_contact_phone'] = df[~df['phone'].astype( str).str.contains(pat=r'^(?:(?!^.{,7}$|^.{16,}$).)*$', case=False, na=False)]['phone'] df['phone'] = df[df['phone'].astype(str).str.contains( pat=r'^(?:(?!^.{,7}$|^.{16,}$).)*$', case=False, na=False)]['phone'] # merges columns so original second_contact_email doesn't get replaced by temp_second_contact_email df['second_contact_phone'] = df[ 'second_contact_phone'].astype(str).fillna( '' ) + ', ' + df['temp_second_contact_phone'].astype( str).fillna('') del df['temp_second_contact_phone'] # this is to just clean up column (i.e. remove leadning what space, random extra commas from merge, and random .0) df['second_contact_phone'] = df[ 'second_contact_phone'].replace( '((, )$|[,]$|(^\s)|(\.0))', '', regex=True) # definitely not needed but one case bothered me so I added it df['second_contact_phone'] = df[ 'second_contact_phone'].replace('( )', ' ', regex=True) # gets rid of random nan that pops up sometimes df = df.replace('(?:^|\W)nan(?:$|\W)', '', regex=True) # these two just cleans up the file and gets rid of random commas. Not really necessary but you know makes the file less ugly df = df.replace('^(, )|^(,)', '', regex=True) df = df.replace('(, , )', ', ', regex=True) # Convert names back from ex. first_name so system auto catches it df.columns = [i.title().replace('_', ' ') for i in df.columns] done = df.to_csv(index=False) end_time = time.time() runtime = end_time - start_time print(runtime) response = HttpResponse(done, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="done.csv"' return response except Exception as e: logging.getLogger("error_logger").error("Unable to upload file. " + repr(e)) messages.error(request, "Unable to upload file. " + repr(e)) return HttpResponseRedirect(reverse("cleancsv:upload_csv"))
def handle_no_permission(self): if self.raise_exception: raise PermissionDenied(self.get_permission_denied_message()) messages.error(self.request, self.get_permission_denied_message()) return redirect(reverse('dashboard'))
def form_invalid(self, form): messages.error(self.request, _('We could not save your changes. See below for details.')) return super().form_invalid(form)
def register(self, postData, request): if User.objects.filter(username=postData['username']).exists(): messages.error(request, 'username is already in our database.') return False else: flag = True if len(postData['name']) < 2: messages.error( request, 'Your first name must be at least two characters.') flag = False if len(postData['username']) < 2: messages.error( request, 'Your last name must be at least 2 characters.') flag = False if not re.match('^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$', postData['email']): messages.error(request, 'Your email format is incorrect.') flag = False if len(postData['password']) < 8: messages.error(request, 'Password must be at least 8 characters.') flag = False if postData['password'] != postData['confirm_password']: messages.error( request, 'Your password does not match your password confirmation.') flag = False if flag == True: password = bcrypt.hashpw(str(postData['password']), bcrypt.gensalt()) User.objects.create(name=postData['name'], username=postData['username'], email=postData['email'], password=password) request.session['id'] = User.objects.only('id').get( email=postData['email']).id request.session['name'] = postData['name'] return True if flag == False: return False
def form_invalid(self, form): messages.error(self.request, _('We could not send the email. See below for details.')) return super().form_invalid(form)
def apagar(request, hash): db_slug = 'default' try: usuario_id = request.user.id dict_hash = get_hash_url(hash) s2300_exterior_id = int(dict_hash['id']) for_print = int(dict_hash['print']) except: usuario_id = False return redirect('login') usuario = get_object_or_404(Usuarios.objects.using(db_slug), excluido=False, id=usuario_id) pagina = ConfigPaginas.objects.using(db_slug).get( excluido=False, endereco='s2300_exterior') permissao = ConfigPermissoes.objects.using(db_slug).get( excluido=False, config_paginas=pagina, config_perfis=usuario.config_perfis) dict_permissoes = json_to_dict(usuario.config_perfis.permissoes) paginas_permitidas_lista = usuario.config_perfis.paginas_permitidas modulos_permitidos_lista = usuario.config_perfis.modulos_permitidos s2300_exterior = get_object_or_404(s2300exterior.objects.using(db_slug), excluido=False, id=s2300_exterior_id) dados_evento = {} if s2300_exterior_id: dados_evento = s2300_exterior.evento() if dados_evento['status'] != 0: dict_permissoes['s2300_exterior_apagar'] = 0 dict_permissoes['s2300_exterior_editar'] = 0 if request.method == 'POST': if dados_evento['status'] == 0: import json from django.forms.models import model_to_dict situacao_anterior = json.dumps(model_to_dict(s2300_exterior), indent=4, sort_keys=True, default=str) s2300exterior.objects.using(db_slug).filter( id=s2300_exterior_id).delete() #s2300_exterior_apagar_custom #s2300_exterior_apagar_custom messages.success(request, 'Apagado com sucesso!') gravar_auditoria(situacao_anterior, '', 's2300_exterior', s2300_exterior_id, usuario_id, 3) else: messages.error( request, 'Não foi possivel apagar o evento, somente é possível apagar os eventos com status "Cadastrado"!' ) if request.session['retorno_pagina'] == 's2300_exterior_salvar': return redirect('s2300_exterior', hash=request.session['retorno_hash']) else: return redirect(request.session['retorno_pagina'], hash=request.session['retorno_hash']) context = { 'usuario': usuario, 'modulos_permitidos_lista': modulos_permitidos_lista, 'paginas_permitidas_lista': paginas_permitidas_lista, 'permissao': permissao, 'data': datetime.datetime.now(), 'pagina': pagina, 'dict_permissoes': dict_permissoes, 'hash': hash, } return render(request, 's2300_exterior_apagar.html', context)
def create_ccx(request, course, ccx=None): """ Create a new CCX """ name = request.POST.get('name') if hasattr(course, 'ccx_connector') and course.ccx_connector: # if ccx connector url is set in course settings then inform user that he can # only create ccx by using ccx connector url. context = get_ccx_creation_dict(course) messages.error(request, context['use_ccx_con_error_message']) return render_to_response('ccx/coach_dashboard.html', context) # prevent CCX objects from being created for deprecated course ids. if course.id.deprecated: messages.error(request, _( "You cannot create a CCX from a course using a deprecated id. " "Please create a rerun of this course in the studio to allow " "this action.")) url = reverse('ccx_coach_dashboard', kwargs={'course_id': course.id}) return redirect(url) ccx = CustomCourseForEdX( course_id=course.id, coach=request.user, display_name=name) ccx.save() # Make sure start/due are overridden for entire course start = TODAY().replace(tzinfo=pytz.UTC) override_field_for_ccx(ccx, course, 'start', start) override_field_for_ccx(ccx, course, 'due', None) # Enforce a static limit for the maximum amount of students that can be enrolled override_field_for_ccx(ccx, course, 'max_student_enrollments_allowed', settings.CCX_MAX_STUDENTS_ALLOWED) # Save display name explicitly override_field_for_ccx(ccx, course, 'display_name', name) # Hide anything that can show up in the schedule hidden = 'visible_to_staff_only' for chapter in course.get_children(): override_field_for_ccx(ccx, chapter, hidden, True) for sequential in chapter.get_children(): override_field_for_ccx(ccx, sequential, hidden, True) for vertical in sequential.get_children(): override_field_for_ccx(ccx, vertical, hidden, True) ccx_id = CCXLocator.from_course_locator(course.id, six.text_type(ccx.id)) # Create forum roles seed_permissions_roles(ccx_id) # Assign administrator forum role to CCX coach assign_role(ccx_id, request.user, FORUM_ROLE_ADMINISTRATOR) url = reverse('ccx_coach_dashboard', kwargs={'course_id': ccx_id}) # Enroll the coach in the course email_params = get_email_params(course, auto_enroll=True, course_key=ccx_id, display_name=ccx.display_name) enroll_email( course_id=ccx_id, student_email=request.user.email, auto_enroll=True, email_students=True, email_params=email_params, ) assign_staff_role_to_ccx(ccx_id, request.user, course.id) add_master_course_staff_to_ccx(course, ccx_id, ccx.display_name) # using CCX object as sender here. responses = SignalHandler.course_published.send( sender=ccx, course_key=CCXLocator.from_course_locator(course.id, six.text_type(ccx.id)) ) for rec, response in responses: log.info(u'Signal fired when course is published. Receiver: %s. Response: %s', rec, response) return redirect(url)
def inquiry(request: AuthHttpRequest, student_id: int) -> HttpResponse: student = get_student_by_id(request, student_id) if not student.semester.active: raise PermissionDenied( "Not an active semester, so change petitions are no longer possible." ) if student.is_delinquent: raise PermissionDenied("Student is delinquent") if not student.enabled: raise PermissionDenied("Student account not enabled") if student.newborn: raise PermissionDenied( "This form isn't enabled yet because you have not chosen your initial units." ) context: Dict[str, Any] = {} current_inquiries = UnitInquiry.objects.filter(student=student) # Create form for submitting new inquiries if request.method == 'POST': form = InquiryForm(request.POST, student=student) if form.is_valid(): inquiry = form.save(commit=False) inquiry.student = student # check if exists already and created recently if UnitInquiry.objects.filter( unit=inquiry.unit, student=student, action_type=inquiry.action_type, created_at__gte=timezone.now() - datetime.timedelta(seconds=90), status="NEW", ).exists(): messages.warning( request, "The same petition already was " "submitted within the last 90 seconds.") else: inquiry.save() num_past_unlock_inquiries = current_inquiries.filter( action_type="UNLOCK").count() unlocked_count = current_inquiries.filter( action_type="UNLOCK", status="NEW").count() + student.unlocked_units.count() # auto reject criteria auto_reject_criteria = inquiry.action_type == "UNLOCK" and unlocked_count > 9 # auto hold criteria num_psets = PSet.objects.filter(student=student).count() auto_hold_criteria = (num_past_unlock_inquiries > (10 + 1.5 * num_psets)) # auto-acceptance criteria auto_accept_criteria = (inquiry.action_type == "APPEND") auto_accept_criteria |= (num_past_unlock_inquiries <= 6 and unlocked_count < 9 and (not auto_hold_criteria and not auto_reject_criteria)) if auto_reject_criteria and not request.user.is_staff: inquiry.status = "REJ" inquiry.save() messages.error( request, "You can't have more than 9 unfinished units unlocked at once." ) elif auto_accept_criteria or request.user.is_staff: inquiry.run_accept() messages.success(request, "Petition automatically approved.") elif auto_hold_criteria: inquiry.status = "HOLD" inquiry.save() messages.warning( request, "You have submitted an abnormally large number of petitions " + "so you should contact Evan specially to explain why.") else: messages.success(request, "Petition submitted, wait for it!") else: form = InquiryForm(student=student) context['form'] = form context['inquiries'] = UnitInquiry.objects.filter(student=student) context['student'] = student context['curriculum'] = student.generate_curriculum_rows( omniscient=can_edit(request, student)) return render(request, 'roster/inquiry.html', context)
def view_listing(request, listing_id): listing = Listing.objects.get(pk=listing_id) comments = Comment.objects.filter(listing=listing) bids = Bid.objects.filter(listing=listing) highest_bid = bids.aggregate(Max('bidding')) you_won = False highest_bidder = False if request.user.is_authenticated: watchlist = Watchlist.objects.filter(user=request.user, item__title=listing.title) watched_items = len( Watchlist.objects.filter(user=request.user, item__status=1)) else: watchlist = None watched_items = 0 # Search for highest bidder and confirm as winner if auction is closed if highest_bid["bidding__max"]: prelim_winner = bids.get(bidding=int(highest_bid['bidding__max'])) if listing.status == False: winner = prelim_winner.user if request.user == winner: you_won = True elif request.user == prelim_winner.user: highest_bidder = True created_by_current_user = (request.user == listing.user ) # Determine signed in user watch_btn = not watchlist # Determine whether listing is already on watchlist if request.method == "POST": bid_form = BidForm(request.POST) comment_form = CommentForm(request.POST) context = { "listing": listing, "bid_form": bid_form, "no_bids": len(bids), "highest_bid": highest_bid, "highest_bidder": highest_bidder, "you_won": you_won, "comment_form": comment_form, "comments": comments, "watch_btn": watch_btn, "watched_items": watched_items } if 'bidding' in request.POST: if bid_form.is_valid(): bidding = bid_form.cleaned_data["bidding"] if (bids and bidding > int(highest_bid['bidding__max'])) or ( not bids and bidding >= listing.starting_bid): new_bidding = Bid(user=request.user, listing=listing, bidding=bidding) new_bidding.save() messages.success(request, 'Your bid was successful!') else: messages.error(request, 'Error! Your bid is too low.') return HttpResponseRedirect( reverse("view_listing", args=(listing_id, ))) else: return render(request, "auctions/view_listing.html", context) elif 'close' in request.POST: listing.status = False listing.save() if highest_bid['bidding__max']: prelim_winner.status = True prelim_winner.save() return HttpResponseRedirect( reverse("view_listing", args=(listing_id, ))) elif 'comment' in request.POST: if comment_form.is_valid(): comment = comment_form.cleaned_data["comment"] new_comment = Comment(listing=listing, comment=comment) new_comment.save() return HttpResponseRedirect( reverse("view_listing", args=(listing_id, ))) else: return render(request, "auctions/view_listing.html", context) elif 'watch' in request.POST: if not watchlist: watch_listing = Watchlist(user=request.user) watch_listing.save() watch_listing.item.add(listing) else: watchlist.delete() return HttpResponseRedirect( reverse("view_listing", args=(listing_id, ))) else: return render( request, "auctions/view_listing.html", { "listing": listing, "bid_form": BidForm(), "no_bids": len(bids), "highest_bid": highest_bid, "highest_bidder": highest_bidder, "you_won": you_won, "comment_form": CommentForm(), "comments": comments, "created_by_current_user": created_by_current_user, "watch_btn": watch_btn, "watched_items": watched_items })
def delete(self, request, *args, **kwargs): booking = self.get_object() # Booking can be fully cancelled if the event allows cancellation AND # the cancellation period is not past # If not, we let people cancel but leave the booking status OPEN and # set to no-show can_cancel_and_refund = booking.event.allow_booking_cancellation \ and booking.event.can_cancel() event_was_full = booking.event.spaces_left == 0 host = 'http://{}'.format(self.request.META.get('HTTP_HOST')) # send email to user ctx = { 'host': host, 'booking': booking, 'event': booking.event, 'date': booking.event.date.strftime('%A %d %B'), 'time': booking.event.date.strftime('%I:%M %p'), } try: send_mail('{} Booking for {} cancelled'.format( settings.ACCOUNT_EMAIL_SUBJECT_PREFIX, booking.event.name), get_template('booking/email/booking_cancelled.txt').render(ctx), settings.DEFAULT_FROM_EMAIL, [booking.user.email], html_message=get_template( 'booking/email/booking_cancelled.html').render(ctx), fail_silently=False) except Exception as e: # send mail to tech support with Exception send_support_email(e, __name__, "DeleteBookingView - cancelled email") messages.error(self.request, "An error occured, please contact " "the studio for information") if can_cancel_and_refund: transfer_block_created = False if booking.paid and (not booking.block or booking.block.expired): # booking was paid directly, either in cash or by paypal # OR booking was free class but not made with free block # OR booking was made with block (normal/free/transfer) but # block has now expired and we can't credit by reassigning # space to block. # NOTE: this does mean that potentially someone could defer # a class indefinitely by cancelling and rebooking, but # let's assume that would be a rare occurrence # If event is CL or RH, get or create transfer block type, # create transfer block for user and set transferred_ # booking_id to the cancelled one if booking.event.event_type.event_type != 'EV': block_type, _ = BlockType.objects.get_or_create( event_type=booking.event.event_type, size=1, cost=0, duration=1, identifier='transferred', active=False ) Block.objects.create( block_type=block_type, user=booking.user, transferred_booking_id=booking.id ) transfer_block_created = True booking.deposit_paid = False booking.paid = False booking.payment_confirmed = False # send email to studio only for 'EV' which are not transferable else: send_mail( '{} {} {} has just cancelled a booking for {}'.format( settings.ACCOUNT_EMAIL_SUBJECT_PREFIX, 'ACTION REQUIRED!' if not booking.block else '', booking.user.username, booking.event.name ), get_template( 'booking/email/to_studio_booking_cancelled.txt' ).render( { 'host': host, 'booking': booking, 'event': booking.event, 'date': booking.event.date.strftime('%A %d %B'), 'time': booking.event.date.strftime('%I:%M %p'), } ), settings.DEFAULT_FROM_EMAIL, [settings.DEFAULT_STUDIO_EMAIL], fail_silently=False) # if booking was bought with a block, remove from block and set # paid and payment_confirmed to False. If paid directly, paid is only # changed to False for bookings that have created transfer blocks; for # EV event types, leave paid as True as refunds need to be dealt with # manually but change payment_confirmed to False # reassigning free class blocks is done in model save if booking.block: booking.block = None booking.paid = False if booking.free_class: booking.free_class = False booking.paid = False booking.status = 'CANCELLED' booking.payment_confirmed = False booking.save() messages.success( self.request, self.success_message.format(booking.event) ) ActivityLog.objects.create( log='Booking id {} for event {}, user {}, was cancelled by user ' '{}'.format( booking.id, booking.event, booking.user.username, self.request.user.username ) ) if transfer_block_created: ActivityLog.objects.create( log='Transfer block created for user {} (for {}; transferred ' 'booking id {} '.format( booking.user.username, booking.event.event_type.subtype, booking.id ) ) messages.info( self.request, mark_safe( 'A transfer block has been created for you as ' 'credit for your cancelled booking and is valid for ' '1 month (<a href="/blocks">View your blocks</a>)' ) ) else: # if the booking wasn't paid, just cancel it if not booking.paid: booking.status = 'CANCELLED' booking.payment_confirmed = False booking.save() messages.success( self.request, self.success_message.format(booking.event) ) ActivityLog.objects.create( log='Booking id {} for event {}, user {}, was cancelled by user ' '{}'.format( booking.id, booking.event, booking.user.username, self.request.user.username ) ) else: # set to no-show booking.no_show = True booking.save() if not booking.event.allow_booking_cancellation: messages.success( self.request, self.success_message.format(booking.event) + ' Please note that this booking is not eligible for refunds ' 'or transfer credit.' ) ActivityLog.objects.create( log='Booking id {} for NON-CANCELLABLE event {}, user {}, ' 'was cancelled and set to no-show'.format( booking.id, booking.event, booking.user.username, self.request.user.username ) ) else: messages.success( self.request, self.success_message.format(booking.event) + ' Please note that this booking is not eligible for ' 'refunds or transfer credit as the allowed ' 'cancellation period has passed.' ) ActivityLog.objects.create( log='Booking id {} for event {}, user {}, was cancelled ' 'after the cancellation period and set to ' 'no-show'.format( booking.id, booking.event, booking.user.username, self.request.user.username ) ) # if applicable, email users on waiting list if event_was_full: waiting_list_users = WaitingListUser.objects.filter( event=booking.event ) if waiting_list_users: try: send_waiting_list_email( booking.event, [wluser.user for wluser in waiting_list_users], host='http://{}'.format(request.META.get('HTTP_HOST')) ) ActivityLog.objects.create( log='Waiting list email sent to user(s) {} for ' 'event {}'.format( ', '.join( [wluser.user.username for \ wluser in waiting_list_users] ), booking.event ) ) except Exception as e: # send mail to tech support with Exception send_support_email(e, __name__, "DeleteBookingView - waiting list email") messages.error(self.request, "An error occured, please contact " "the studio for information") return HttpResponseRedirect(self.get_success_url())
def register(request: AuthHttpRequest) -> HttpResponse: try: container = RegistrationContainer.objects.get(semester__active=True) except (RegistrationContainer.DoesNotExist, RegistrationContainer.MultipleObjectsReturned): return HttpResponse("There isn't a currently active OTIS semester.", status=503) semester: Semester = container.semester if StudentRegistration.objects.filter(user=request.user, container=container).exists(): messages.info( request, message="You have already submitted a decision form for this year!" ) form = None elif request.method == 'POST': form = DecisionForm(request.POST, request.FILES) if form.is_valid(): passcode = form.cleaned_data['passcode'] if passcode.lower() != container.passcode.lower(): messages.error(request, message="Wrong passcode") elif form.cleaned_data[ 'track'] not in container.allowed_tracks.split(','): messages.error( request, message= "That track is not currently accepting registrations.") else: registration = form.save(commit=False) registration.container = container registration.user = request.user registration.save() request.user.first_name = form.cleaned_data[ 'given_name'].strip() request.user.last_name = form.cleaned_data['surname'].strip() request.user.email = form.cleaned_data['email_address'] group, _ = Group.objects.get_or_create(name='Verified') group.user_set.add(request.user) # type: ignore request.user.save() mailchimp_subscribe(request) messages.success(request, message="Submitted! Sit tight.") logger.log( ACTION_LOG_LEVEL, f'New registration from {request.user.get_full_name()}', extra={'request': request}, ) return HttpResponseRedirect(reverse("index")) else: if container.allowed_tracks: initial_data_dict = {} most_recent_reg = StudentRegistration.objects.filter( user=request.user, ).order_by('-id').first() if most_recent_reg is not None: for k in ('parent_email', 'graduation_year', 'school_name', 'aops_username', 'gender'): initial_data_dict[k] = getattr(most_recent_reg, k) form = DecisionForm(initial=initial_data_dict) else: messages.warning( request, message= "The currently active semester isn't accepting registrations right now." ) form = None context = { 'title': f'{semester} Decision Form', 'form': form, 'container': container } return render(request, 'roster/decision_form.html', context)
def form_valid(self, form): booking = form.save(commit=False) try: # We shouldn't even get here with a booking that isn't either # cancelled or no_show; those get redirected in the dispatch() existing_booking = Booking.objects.get( user=self.request.user, event=booking.event, ) booking = existing_booking if booking.status == 'CANCELLED': previously_cancelled = True previously_no_show = False elif booking.no_show: previously_no_show = True previously_cancelled = False booking.status = 'OPEN' booking.no_show = False except Booking.DoesNotExist: previously_cancelled = False previously_no_show = False booking.user = self.request.user transaction_id = None invoice_id = None previously_cancelled_and_direct_paid = False if "claim_free" in form.data: _email_free_class_request( self.request, booking, 'rebook' if previously_cancelled else 'create' ) elif previously_cancelled and booking.paid: previously_cancelled_and_direct_paid = True pptrans = PaypalBookingTransaction.objects.filter(booking=booking)\ .exclude(transaction_id__isnull=True) if pptrans: transaction_id = pptrans[0].transaction_id invoice_id = pptrans[0].invoice_id elif previously_no_show and booking.paid: # leave paid no_show booking with existing payment method pass elif 'block_book' in form.data: active_block = _get_active_user_block(self.request.user, booking) if active_block: booking.block = active_block booking.paid = True booking.payment_confirmed = True # check for existence of free child block on pre-saved booking # note for prev no-shows booked with block, any free child blocks should # have already been created. Rebooking prev no-show doesn;t add a new # block booking has_free_block_pre_save = False if booking.block and booking.block.children.exists(): has_free_block_pre_save = True try: booking.save() ActivityLog.objects.create( log='Booking {} {} for "{}" by user {}'.format( booking.id, 'created' if not (previously_cancelled or previously_no_show) else 'rebooked', booking.event, booking.user.username) ) except ValidationError: # pragma: no cover # we shouldn't ever get here, because the dispatch should deal # with it logger.warning( 'Validation error, most likely due to duplicate booking ' 'attempt; redirected to duplicate booking page' ) return HttpResponseRedirect(reverse('booking:duplicate_booking', args=[self.event.slug])) # set flag on session so if user clicks "back" after posting the form, # we can redirect self.request.session['booking_created_{}'.format(booking.id)] = True blocks_used, total_blocks = _get_block_status(booking, self.request) host = 'http://{}'.format(self.request.META.get('HTTP_HOST')) # send email to user ctx = { 'host': host, 'booking': booking, 'event': booking.event, 'date': booking.event.date.strftime('%A %d %B'), 'time': booking.event.date.strftime('%H:%M'), 'blocks_used': blocks_used, 'total_blocks': total_blocks, 'prev_cancelled_and_direct_paid': previously_cancelled_and_direct_paid, 'claim_free': True if "claim_free" in form.data else False, 'ev_type': self.ev_type[:-1] } try: send_mail('{} Booking for {}'.format( settings.ACCOUNT_EMAIL_SUBJECT_PREFIX, booking.event.name), get_template('booking/email/booking_received.txt').render(ctx), settings.DEFAULT_FROM_EMAIL, [booking.user.email], html_message=get_template( 'booking/email/booking_received.html' ).render(ctx), fail_silently=False) except Exception as e: # send mail to tech support with Exception send_support_email(e, __name__, "BookingCreateView") messages.error(self.request, "An error occured, please contact " "the studio for information") # send email to studio if flagged for the event or if previously # cancelled and direct paid if (booking.event.email_studio_when_booked or previously_cancelled_and_direct_paid): additional_subject = "" if previously_cancelled_and_direct_paid: additional_subject = "ACTION REQUIRED!" try: send_mail('{} {} {} {} has just booked for {}'.format( settings.ACCOUNT_EMAIL_SUBJECT_PREFIX, additional_subject, booking.user.first_name, booking.user.last_name, booking.event.name), get_template( 'booking/email/to_studio_booking.txt' ).render( { 'host': host, 'booking': booking, 'event': booking.event, 'date': booking.event.date.strftime('%A %d %B'), 'time': booking.event.date.strftime('%H:%M'), 'prev_cancelled_and_direct_paid': previously_cancelled_and_direct_paid, 'transaction_id': transaction_id, 'invoice_id': invoice_id } ), settings.DEFAULT_FROM_EMAIL, [settings.DEFAULT_STUDIO_EMAIL], fail_silently=False) except Exception as e: # send mail to tech support with Exception send_support_email(e, __name__, "BookingCreateView") extra_msg = '' if 'claim_free' in form.data: extra_msg = 'Your place will be secured once your free class ' \ 'request has been reviewed and approved. ' elif previously_cancelled_and_direct_paid: extra_msg = 'You previously paid for this booking; your booking ' \ 'will remain as pending until the organiser has ' \ 'reviewed your payment status.' elif previously_no_show: if booking.block: extra_msg = "You previously paid for this booking with a " \ "block and your booking has been reopened." elif booking.paid: extra_msg = "You previously paid for this booking and your " \ "booking has been reopened." elif not booking.block: if booking.event.cost and not booking.paid: # prev no_show could still be paid cancellation_warning = "" if booking.event.advance_payment_required and \ booking.event.allow_booking_cancellation: if booking.event.payment_due_date: cancel_str = "by the payment due date" elif booking.event.payment_time_allowed: cancel_str = "within {} hours".format( booking.event.payment_time_allowed ) else: cancel_str = "by the cancellation period" cancellation_warning = "Note that if payment " \ "has not been received {}, " \ "your booking will be automatically cancelled.".format( cancel_str ) extra_msg = 'Please make your payment as soon as possible. ' \ '<strong>{}</strong>'.format(cancellation_warning) elif not booking.block.active_block(): transfer_block = booking.block.block_type.identifier\ .startswith('transferred') \ if booking.block.block_type.identifier else False if not transfer_block: extra_msg = 'You have just used the last space in your block. ' if booking.block.children.exists() and not has_free_block_pre_save: extra_msg += '</br><span style="color: #9A2EFE;">' \ '<strong>You have qualified for a extra free ' \ 'class which has been added to ' \ '<a href="/blocks">your blocks</a></strong><span> ' else: extra_msg += 'Go to <a href="/blocks">Your Blocks</a> to ' \ 'buy a new one.' messages.success( self.request, mark_safe("{}<br>{}".format( self.success_message.format(booking.event), extra_msg)) ) try: waiting_list_user = WaitingListUser.objects.get( user=booking.user, event=booking.event ) waiting_list_user.delete() ActivityLog.objects.create( log='User {} removed from waiting list ' 'for {}'.format( booking.user.username, booking.event ) ) except WaitingListUser.DoesNotExist: pass if not booking.paid and booking.event.cost: return HttpResponseRedirect( reverse('booking:update_booking', args=[booking.id]) ) return HttpResponseRedirect(reverse('booking:bookings'))
def flash_errors(errors, request): print '*****log_reg flash_errors method*****' for error in errors: messages.error(request, error)
def checkout(request): stripe_public_key = settings.STRIPE_PUBLIC_KEY stripe_secret_key = settings.STRIPE_SECRET_KEY if request.method == 'POST': bag = request.session.get('bag', {}) form_data = { 'full_name': request.POST['full_name'], 'email': request.POST['email'], 'phone_number': request.POST['phone_number'], 'country': request.POST['country'], 'postcode': request.POST['postcode'], 'town_or_city': request.POST['town_or_city'], 'street_address1': request.POST['street_address1'], 'street_address2': request.POST['street_address2'], 'county': request.POST['county'], } order_form = OrderForm(form_data) if order_form.is_valid(): order = order_form.save(commit=False) pid = request.POST.get('client_secret').split('_secret')[0] order.stripe_pid = pid order.original_bag = json.dumps(bag) order.save() for item_id, item_data in bag.items(): try: product = Product.objects.get(id=item_id) if isinstance(item_data, int): order_line_item = OrderLineItem( order=order, product=product, quantity=item_data, ) order_line_item.save() else: for size, quantity in item_data['items_by_size'].items(): order_line_item = OrderLineItem( order=order, product=product, quantity=quantity, product_size=size, ) order_line_item.save() except Product.DoesNotExist: messages.error(request, ( "One of the products in your bag wasn't found in our database. " "Please call us for assistance!") ) order.delete() return redirect(reverse('view_bag')) # Save the info to the user's profile if all is well request.session['save_info'] = 'save-info' in request.POST return redirect(reverse('checkout_success', args=[order.order_number])) else: messages.error(request, 'There was an error with your form. \ Please double check your information.') else: bag = request.session.get('bag', {}) if not bag: messages.error( request, "There's nothing in your bag at the moment") return redirect(reverse('products')) current_bag = bag_contents(request) total = current_bag['grand_total'] stripe_total = round(total * 100) stripe.api_key = stripe_secret_key intent = stripe.PaymentIntent.create( amount=stripe_total, currency=settings.STRIPE_CURRENCY, ) # Attempt to prefill the form with any info the user maintains in their profile if request.user.is_authenticated: try: profile = UserProfile.objects.get(user=request.user) order_form = OrderForm(initial={ 'full_name': profile.default_full_name, 'email': profile.user.email, 'phone_number': profile.default_phone_number, 'country': profile.default_country, 'postcode': profile.default_postcode, 'town_or_city': profile.default_town_or_city, 'street_address1': profile.default_street_address1, 'street_address2': profile.default_street_address2, 'county': profile.default_county, }) except UserProfile.DoesNotExist: order_form = OrderForm() else: order_form = OrderForm() if not stripe_public_key: messages.warning(request, 'Stripe public key is missing. \ Did you forget to set it in your environment?') template = 'checkout/checkout.html' context = { 'order_form': order_form, 'stripe_public_key': stripe_public_key, 'client_secret': intent.client_secret, } return render(request, template, context)
def form_valid(self, form): if "apply_voucher" in form.data: code = form.data['code'].strip() try: voucher = EventVoucher.objects.get(code=code) except EventVoucher.DoesNotExist: voucher = None voucher_error = 'Invalid code' if code else 'No code provided' if voucher: voucher_error = self.validate_voucher_code( voucher, self.request.user, self.object.event ) context = self.get_context_data( voucher=voucher, voucher_error=voucher_error, code=code ) return TemplateResponse(self.request, self.template_name, context) booking = form.save(commit=False) if "claim_free"in form.data: _email_free_class_request(self.request, booking, 'update') elif 'block_book' in form.data: active_block = _get_active_user_block(self.request.user, booking) if active_block: booking.block = active_block booking.paid = True booking.payment_confirmed = True else: messages.error(self.request, 'Error: No available block') # check for existence of free child block on pre-saved booking has_free_block_pre_save = False if booking.block and booking.block.children.exists(): has_free_block_pre_save = True booking.save() blocks_used, total_blocks = _get_block_status(booking, self.request) if booking.block: # send email to user if they used block to book (paypal payment # sends separate emails host = 'http://{}'.format(self.request.META.get('HTTP_HOST')) if booking.event.event_type.event_type == 'EV': ev_type = 'event' elif booking.event.event_type.event_type == 'CL': ev_type = 'class' else: ev_type = 'room hire' ctx = { 'host': host, 'booking': booking, 'event': booking.event, 'date': booking.event.date.strftime('%A %d %B'), 'time': booking.event.date.strftime('%I:%M %p'), 'blocks_used': blocks_used, 'total_blocks': total_blocks, 'ev_type': ev_type } send_mail('{} Block used for booking for {}'.format( settings.ACCOUNT_EMAIL_SUBJECT_PREFIX, booking.event.name), get_template('booking/email/booking_updated.txt').render(ctx), settings.DEFAULT_FROM_EMAIL, [booking.user.email], html_message=get_template( 'booking/email/booking_updated.html').render(ctx), fail_silently=False) messages.success( self.request, self.success_message.format(booking.event) ) if booking.block and not booking.block.active_block(): msg = 'You have just used the last space in your block. ' if booking.block.children.exists() \ and not has_free_block_pre_save: msg += 'You have qualified for a extra free ' \ 'class which has been added to ' \ '<a href="/blocks">your blocks</a>! ' else: msg += 'Go to <a href="/blocks">Your Blocks</a> to ' \ 'buy a new one.' messages.info(self.request, mark_safe(msg)) return HttpResponseRedirect(self.get_success_url())
def edit_student_save(request): if request.method != "POST": return HttpResponse("<h2>Method Not Allowed</h2>") else: student_id = request.session.get("student_id") if student_id == None: return HttpResponseRedirect(reverse("manage_student")) form = EditStudentForm(request.POST, request.FILES) if form.is_valid(): first_name = form.cleaned_data["first_name"] last_name = form.cleaned_data["last_name"] username = form.cleaned_data["username"] email = form.cleaned_data["email"] address = form.cleaned_data["address"] # session_start = form.cleaned_data["session_start"] # session_end = form.cleaned_data["session_end"] course_id = form.cleaned_data["course"] sex = form.cleaned_data["sex"] if request.FILES.get('profile_pic', False): profile_pic = request.FILES['profile_pic'] fs = FileSystemStorage() filename = fs.save(profile_pic.name, profile_pic) profile_pic_url = fs.url(filename) else: profile_pic_url = None try: user = CustomUser.objects.get(id=student_id) user.first_name = first_name user.last_name = last_name user.username = username user.email = email user.save() student = Students.objects.get(admin=student_id) student.address = address # student.session_start_year=session_start # student.session_end_year=session_end student.gender = sex course = Courses.objects.get(id=course_id) student.course_id = course if profile_pic_url != None: student.profile_pic = profile_pic_url student.save() del request.session['student_id'] messages.success(request, "Successfully Edited Student") return HttpResponseRedirect( reverse("edit_student", kwargs={"student_id": student_id})) except: messages.error(request, "Failed to Edit Student") return HttpResponseRedirect( reverse("edit_student", kwargs={"student_id": student_id})) else: form = EditStudentForm(request.POST) student = Students.objects.get(admin=student_id) return render(request, "hod_template/edit_student_template.html", { "form": form, "id": student_id, "username": student.admin.username })
def salvar(request, pk=None, tab='master', output=None): from emensageriapro.efdreinf.models import STATUS_EVENTO_CADASTRADO from emensageriapro.settings import VERSAO_EMENSAGERIA, VERSAO_LAYOUT_EFDREINF TP_AMB = config.EFDREINF_TP_AMB if pk: r9011_evttotalcontrib = get_object_or_404(r9011evtTotalContrib, id=pk) if r9011_evttotalcontrib.status != STATUS_EVENTO_CADASTRADO: dict_permissoes = {} dict_permissoes['r9011_evttotalcontrib_apagar'] = 0 dict_permissoes['r9011_evttotalcontrib_editar'] = 0 if request.user.has_perm('efdreinf.can_see_r9011evtTotalContrib'): if pk: r9011_evttotalcontrib_form = form_r9011_evttotalcontrib( request.POST or None, instance=r9011_evttotalcontrib, initial={'ativo': True}) else: r9011_evttotalcontrib_form = form_r9011_evttotalcontrib( request.POST or None, initial={ 'versao': VERSAO_LAYOUT_EFDREINF, 'status': STATUS_EVENTO_CADASTRADO, 'tpamb': TP_AMB, 'procemi': 1, 'verproc': VERSAO_EMENSAGERIA, 'ativo': True }) if request.method == 'POST': if r9011_evttotalcontrib_form.is_valid(): obj = r9011_evttotalcontrib_form.save(request=request) messages.success(request, u'Salvo com sucesso!') if not pk: from emensageriapro.functions import identidade_evento identidade_evento(obj) gravar_auditoria( '{}', json.dumps(model_to_dict(obj), indent=4, sort_keys=True, default=str), 'r9011_evttotalcontrib', obj.id, request.user.id, 1) else: gravar_auditoria( json.dumps(model_to_dict(r9011_evttotalcontrib), indent=4, sort_keys=True, default=str), json.dumps(model_to_dict(obj), indent=4, sort_keys=True, default=str), 'r9011_evttotalcontrib', pk, request.user.id, 2) if request.session['return_page'] not in ( 'r9011_evttotalcontrib_apagar', 'r9011_evttotalcontrib_salvar', 'r9011_evttotalcontrib'): return redirect(request.session['return_page'], pk=request.session['return_pk']) if pk != obj.id: return redirect('r9011_evttotalcontrib_salvar', pk=obj.id) else: messages.error(request, u'Erro ao salvar!') r9011_evttotalcontrib_form = disabled_form_fields( r9011_evttotalcontrib_form, request.user.has_perm('efdreinf.change_r9011evtTotalContrib')) if pk: if r9011_evttotalcontrib.status != 0: r9011_evttotalcontrib_form = disabled_form_fields( r9011_evttotalcontrib_form, False) #r9011_evttotalcontrib_campos_multiple_passo3 for field in r9011_evttotalcontrib_form.fields.keys(): r9011_evttotalcontrib_form.fields[field].widget.attrs[ 'ng-model'] = 'r9011_evttotalcontrib_' + field if output: r9011_evttotalcontrib_form = disabled_form_for_print( r9011_evttotalcontrib_form) r1000_evtinfocontri_lista = None r1000_evtinfocontri_form = None r1070_evttabprocesso_lista = None r1070_evttabprocesso_form = None r2010_evtservtom_lista = None r2010_evtservtom_form = None r2020_evtservprest_lista = None r2020_evtservprest_form = None r2030_evtassocdesprec_lista = None r2030_evtassocdesprec_form = None r2040_evtassocdesprep_lista = None r2040_evtassocdesprep_form = None r2050_evtcomprod_lista = None r2050_evtcomprod_form = None r2060_evtcprb_lista = None r2060_evtcprb_form = None r2070_evtpgtosdivs_lista = None r2070_evtpgtosdivs_form = None r2098_evtreabreevper_lista = None r2098_evtreabreevper_form = None r2099_evtfechaevper_lista = None r2099_evtfechaevper_form = None r3010_evtespdesportivo_lista = None r3010_evtespdesportivo_form = None r4010_evtretpf_lista = None r4010_evtretpf_form = None r4020_evtretpj_lista = None r4020_evtretpj_form = None r4040_evtbenefnid_lista = None r4040_evtbenefnid_form = None r4098_evtreab_lista = None r4098_evtreab_form = None r4099_evtfech_lista = None r4099_evtfech_form = None r9000_evtexclusao_lista = None r9000_evtexclusao_form = None r9011_regocorrs_lista = None r9011_regocorrs_form = None r9011_infototalcontrib_lista = None r9011_infototalcontrib_form = None if pk: r9011_evttotalcontrib = get_object_or_404(r9011evtTotalContrib, id=pk) r9011_regocorrs_form = form_r9011_regocorrs( initial={'r9011_evttotalcontrib': r9011_evttotalcontrib}) r9011_regocorrs_form.fields['r9011_evttotalcontrib'].widget.attrs[ 'readonly'] = True r9011_regocorrs_lista = r9011regOcorrs.objects.\ filter(r9011_evttotalcontrib_id=r9011_evttotalcontrib.id).all() r9011_infototalcontrib_form = form_r9011_infototalcontrib( initial={'r9011_evttotalcontrib': r9011_evttotalcontrib}) r9011_infototalcontrib_form.fields[ 'r9011_evttotalcontrib'].widget.attrs['readonly'] = True r9011_infototalcontrib_lista = r9011infoTotalContrib.objects.\ filter(r9011_evttotalcontrib_id=r9011_evttotalcontrib.id).all() r1000_evtinfocontri_form = form_r1000_evtinfocontri( initial={'retornos_r9011': r9011_evttotalcontrib}) r1000_evtinfocontri_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r1000_evtinfocontri_lista = r1000evtInfoContri.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r1070_evttabprocesso_form = form_r1070_evttabprocesso( initial={'retornos_r9011': r9011_evttotalcontrib}) r1070_evttabprocesso_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r1070_evttabprocesso_lista = r1070evtTabProcesso.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r2010_evtservtom_form = form_r2010_evtservtom( initial={'retornos_r9011': r9011_evttotalcontrib}) r2010_evtservtom_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r2010_evtservtom_lista = r2010evtServTom.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r2020_evtservprest_form = form_r2020_evtservprest( initial={'retornos_r9011': r9011_evttotalcontrib}) r2020_evtservprest_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r2020_evtservprest_lista = r2020evtServPrest.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r2030_evtassocdesprec_form = form_r2030_evtassocdesprec( initial={'retornos_r9011': r9011_evttotalcontrib}) r2030_evtassocdesprec_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r2030_evtassocdesprec_lista = r2030evtAssocDespRec.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r2040_evtassocdesprep_form = form_r2040_evtassocdesprep( initial={'retornos_r9011': r9011_evttotalcontrib}) r2040_evtassocdesprep_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r2040_evtassocdesprep_lista = r2040evtAssocDespRep.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r2050_evtcomprod_form = form_r2050_evtcomprod( initial={'retornos_r9011': r9011_evttotalcontrib}) r2050_evtcomprod_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r2050_evtcomprod_lista = r2050evtComProd.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r2060_evtcprb_form = form_r2060_evtcprb( initial={'retornos_r9011': r9011_evttotalcontrib}) r2060_evtcprb_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r2060_evtcprb_lista = r2060evtCPRB.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r2070_evtpgtosdivs_form = form_r2070_evtpgtosdivs( initial={'retornos_r9011': r9011_evttotalcontrib}) r2070_evtpgtosdivs_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r2070_evtpgtosdivs_lista = r2070evtPgtosDivs.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r2098_evtreabreevper_form = form_r2098_evtreabreevper( initial={'retornos_r9011': r9011_evttotalcontrib}) r2098_evtreabreevper_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r2098_evtreabreevper_lista = r2098evtReabreEvPer.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r2099_evtfechaevper_form = form_r2099_evtfechaevper( initial={'retornos_r9011': r9011_evttotalcontrib}) r2099_evtfechaevper_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r2099_evtfechaevper_lista = r2099evtFechaEvPer.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r3010_evtespdesportivo_form = form_r3010_evtespdesportivo( initial={'retornos_r9011': r9011_evttotalcontrib}) r3010_evtespdesportivo_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r3010_evtespdesportivo_lista = r3010evtEspDesportivo.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r4010_evtretpf_form = form_r4010_evtretpf( initial={'retornos_r9011': r9011_evttotalcontrib}) r4010_evtretpf_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r4010_evtretpf_lista = r4010evtRetPF.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r4020_evtretpj_form = form_r4020_evtretpj( initial={'retornos_r9011': r9011_evttotalcontrib}) r4020_evtretpj_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r4020_evtretpj_lista = r4020evtRetPJ.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r4040_evtbenefnid_form = form_r4040_evtbenefnid( initial={'retornos_r9011': r9011_evttotalcontrib}) r4040_evtbenefnid_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r4040_evtbenefnid_lista = r4040evtBenefNId.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r4098_evtreab_form = form_r4098_evtreab( initial={'retornos_r9011': r9011_evttotalcontrib}) r4098_evtreab_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r4098_evtreab_lista = r4098evtReab.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r4099_evtfech_form = form_r4099_evtfech( initial={'retornos_r9011': r9011_evttotalcontrib}) r4099_evtfech_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r4099_evtfech_lista = r4099evtFech.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() r9000_evtexclusao_form = form_r9000_evtexclusao( initial={'retornos_r9011': r9011_evttotalcontrib}) r9000_evtexclusao_form.fields['retornos_r9011'].widget.attrs[ 'readonly'] = True r9000_evtexclusao_lista = r9000evtExclusao.objects.\ filter(retornos_r9011_id=r9011_evttotalcontrib.id).all() else: r9011_evttotalcontrib = None #r9011_evttotalcontrib_salvar_custom_variaveis# tabelas_secundarias = [] #[FUNCOES_ESPECIAIS_SALVAR] if 'r9011_evttotalcontrib'[1] == '5': evento_totalizador = True else: evento_totalizador = False if tab or 'r9011_evttotalcontrib' in request.session['return_page']: request.session['return_pk'] = pk request.session['return_tab'] = tab request.session['return_page'] = 'r9011_evttotalcontrib_salvar' controle_alteracoes = Auditoria.objects.filter( identidade=pk, tabela='r9011_evttotalcontrib').all() context = { 'usuario': Usuarios.objects.get(user_id=request.user.id), 'pk': pk, 'output': output, 'evento_totalizador': evento_totalizador, 'controle_alteracoes': controle_alteracoes, 'r9011_evttotalcontrib': r9011_evttotalcontrib, 'r9011_evttotalcontrib_form': r9011_evttotalcontrib_form, 'r1000_evtinfocontri_form': r1000_evtinfocontri_form, 'r1000_evtinfocontri_lista': r1000_evtinfocontri_lista, 'r1070_evttabprocesso_form': r1070_evttabprocesso_form, 'r1070_evttabprocesso_lista': r1070_evttabprocesso_lista, 'r2010_evtservtom_form': r2010_evtservtom_form, 'r2010_evtservtom_lista': r2010_evtservtom_lista, 'r2020_evtservprest_form': r2020_evtservprest_form, 'r2020_evtservprest_lista': r2020_evtservprest_lista, 'r2030_evtassocdesprec_form': r2030_evtassocdesprec_form, 'r2030_evtassocdesprec_lista': r2030_evtassocdesprec_lista, 'r2040_evtassocdesprep_form': r2040_evtassocdesprep_form, 'r2040_evtassocdesprep_lista': r2040_evtassocdesprep_lista, 'r2050_evtcomprod_form': r2050_evtcomprod_form, 'r2050_evtcomprod_lista': r2050_evtcomprod_lista, 'r2060_evtcprb_form': r2060_evtcprb_form, 'r2060_evtcprb_lista': r2060_evtcprb_lista, 'r2070_evtpgtosdivs_form': r2070_evtpgtosdivs_form, 'r2070_evtpgtosdivs_lista': r2070_evtpgtosdivs_lista, 'r2098_evtreabreevper_form': r2098_evtreabreevper_form, 'r2098_evtreabreevper_lista': r2098_evtreabreevper_lista, 'r2099_evtfechaevper_form': r2099_evtfechaevper_form, 'r2099_evtfechaevper_lista': r2099_evtfechaevper_lista, 'r3010_evtespdesportivo_form': r3010_evtespdesportivo_form, 'r3010_evtespdesportivo_lista': r3010_evtespdesportivo_lista, 'r4010_evtretpf_form': r4010_evtretpf_form, 'r4010_evtretpf_lista': r4010_evtretpf_lista, 'r4020_evtretpj_form': r4020_evtretpj_form, 'r4020_evtretpj_lista': r4020_evtretpj_lista, 'r4040_evtbenefnid_form': r4040_evtbenefnid_form, 'r4040_evtbenefnid_lista': r4040_evtbenefnid_lista, 'r4098_evtreab_form': r4098_evtreab_form, 'r4098_evtreab_lista': r4098_evtreab_lista, 'r4099_evtfech_form': r4099_evtfech_form, 'r4099_evtfech_lista': r4099_evtfech_lista, 'r9000_evtexclusao_form': r9000_evtexclusao_form, 'r9000_evtexclusao_lista': r9000_evtexclusao_lista, 'r9011_regocorrs_form': r9011_regocorrs_form, 'r9011_regocorrs_lista': r9011_regocorrs_lista, 'r9011_infototalcontrib_form': r9011_infototalcontrib_form, 'r9011_infototalcontrib_lista': r9011_infototalcontrib_lista, 'data': datetime.datetime.now(), 'modulos': [ 'efdreinf', ], 'paginas': [ 'r9011_evttotalcontrib', ], 'tabelas_secundarias': tabelas_secundarias, 'tab': tab, #r9011_evttotalcontrib_salvar_custom_variaveis_context# } if output == 'pdf': response = PDFTemplateResponse( request=request, template='r9011_evttotalcontrib_salvar.html', filename="r9011_evttotalcontrib.pdf", context=context, show_content_in_browser=True, cmd_options={ 'margin-top': 10, 'margin-bottom': 10, 'margin-right': 10, 'margin-left': 10, 'zoom': 1, 'dpi': 72, 'orientation': 'Landscape', "viewport-size": "1366 x 513", 'javascript-delay': 1000, 'footer-center': '[page]/[topage]', "no-stop-slow-scripts": True }, ) return response elif output == 'xls': response = render_to_response('r9011_evttotalcontrib_salvar.html', context) filename = "r9011_evttotalcontrib.xls" response[ 'Content-Disposition'] = 'attachment; filename=' + filename response[ 'Content-Type'] = 'application/vnd.ms-excel; charset=UTF-8' return response else: return render(request, 'r9011_evttotalcontrib_salvar.html', context) else: context = { 'usuario': Usuarios.objects.get(user_id=request.user.id), 'pk': pk, 'tab': tab, 'output': output, 'modulos': [ 'efdreinf', ], 'paginas': [ 'r9011_evttotalcontrib', ], 'data': datetime.datetime.now(), } return render(request, 'permissao_negada.html', context)
def post(self, request, *args, **kwargs): """ Expected data submitted from the form: 1) New billing periods have field names ending in a matching number. - '<field>_new(\d+)' for BillingPeriod fields - 'invoice_amount_group(<pk of group>)_new(\d+)' 2) Existing billing periods have field names formatted as: - '<field>(<pk of BillingPeriod>)' for BillingPeriod fields - 'invoice_amount_group(<pk of group>)_(<pk of BillingPeriod>)' - NOTE: You can change the due_date of all associated invoices by updating the date here. 3) Deleted billing periods show up as hidden inputs: - 'delete(<pk of BillingPeriod>)' - NOTE: You cannot delete any billing periods with invoices already generated """ new_regex = re.compile('^name_new(\d+)$') existing_regex = re.compile('^name(\d+)$') delete_regex = re.compile('^delete(\d+)$') billing_groups = BillingGroup.objects.filter(league=self.league) error_messages = [] alert_messages = [] new_periods = [] updated_periods = [] deleted_periods = [] post = request.POST for key, value in post.items(): new_match = new_regex.match(key) existing_match = existing_regex.match(key) delete_match = delete_regex.match(key) print("{} {}".format(key, new_match)) if new_match: # Add a NEW billing period bp_id = '_new{}'.format(new_match.group(1)) bp = BillingPeriod() bp.event = self.event bp.league = self.league try: bp.name = post['name{}'.format(bp_id)] if bp.name == "": # Ignore anything with a blank name. continue bp.start_date = datetime.strptime( post['start_date{}'.format(bp_id)], '%m/%d/%y' ) bp.end_date = datetime.strptime( post['end_date{}'.format(bp_id)], '%m/%d/%y' ) bp.invoice_date = datetime.strptime( post['invoice_date{}'.format(bp_id)], '%m/%d/%y' ) bp.due_date = datetime.strptime( post['due_date{}'.format(bp_id)], '%m/%d/%y' ) except KeyError as e: alert_messages.append("Field not found for NEW billing period. Error: {}".format(str(e))) continue except ValueError as e: error_messages.append("Invalid date specified for new due date for '{}'. Error: {}".format(bp.name, str(e))) try: bp.full_clean() except ValidationError as e: error_messages.append("Invalid data in new row. Please try again. Error: {}".format(str(e))) else: bp.save() new_periods.append(bp) for group in billing_groups: bpcpa = BillingPeriodCustomPaymentAmount() bpcpa.group = group bpcpa.period = bp try: if post['invoice_amount_group{}{}'.format(group.pk, bp_id)] is None: bpcpa.invoice_amount = Decimal('0.00') else: bpcpa.invoice_amount = post['invoice_amount_group{}{}'.format(group.pk, bp_id)] except KeyError as e: alert_messages.append("Field not found for NEW billing period. Error: {}".format(str(e))) continue try: bpcpa.full_clean() except ValidationError as e: error_messages.append("Invalid data in new row, for group amount set for '{}' price. Please try again. Error: {}".format(group.name, str(e))) else: bpcpa.save() elif existing_match: # Update an EXISTING billing period # If there are attached invoices you can update the due_date by # just changing it here. bp_id = '{}'.format(existing_match.group(1)) bp_pk = existing_match.group(1) changed = False try: bp = BillingPeriod.objects.get(pk=bp_pk) except BillingPeriod.DoesNotExist as e: error_messages.append("Not able to find Billing Period with ID #{}. Error: {}".format(bp_pk, str(e))) # Check if user currently has access to this billing period. # If the current viewing league matches (already checked), # allow them access. # If they don't have access then just continue silently, I guess. # TODO: do something else if there's a permissions issue? if bp.league.pk != self.league.pk: error_messages.append("You don't seem to have permission to access a Billing Period in this form. Not sure how that happened. I can't save it.") try: new_invoice_date = datetime.strptime( post['invoice_date{}'.format(bp_id)], '%m/%d/%y' ) except KeyError as e: alert_messages.append("Field not found for '{}' when saving billing period. Field was 'invoice_date{}'' . Error: {}".format(bp, bp_id, str(e))) except ValueError as e: error_messages.append("Invalid date specified for invoice date for '{}'. Value was '{}'. Error: {}".format(bp, post['invoice_date{}'.format(bp_id)], str(e))) if new_invoice_date.date() != bp.invoice_date: # If the invoice date has already passed, do not allow them to update it. if timezone.now().date() < bp.invoice_date: changed = True bp.invoice_date = new_invoice_date else: alert_messages.append("You cannot update invoice date for '{}'. The date has already passed.".format(bp)) try: new_due_date = datetime.strptime( post['due_date{}'.format(bp_id)], '%m/%d/%y' ) except KeyError as e: alert_messages.append("Field not found for '{}' when saving billing period. Field was 'invoice_date{}'' . Error: {}".format(bp, bp_id, str(e))) except ValueError as e: error_messages.append("Invalid date specified for due date for '{}'. Value was '{}'. Error: {}".format(bp, post['invoice_date{}'.format(bp_id)], str(e))) if new_due_date.date() != bp.due_date: # If the due date has already passed, do not allow them to update it. if timezone.now().date() < bp.due_date: changed = True bp.due_date = new_due_date else: alert_messages.append("You cannot update due date for '{}'. The date has already passed.".format(bp)) try: new_start_date = datetime.strptime( post['start_date{}'.format(bp_id)], '%m/%d/%y', ) new_end_date = datetime.strptime( post['end_date{}'.format(bp_id)], '%m/%d/%y', ) new_name = post['name{}'.format(bp_id)] except KeyError as e: alert_messages.append("Field not found for '{}' when saving billing period. Error: {}".format(bp, str(e))) if new_start_date.date() != bp.start_date: changed = True bp.start_date = new_start_date if new_end_date.date() != bp.end_date: changed = True bp.end_date = new_end_date if new_name != bp.name: changed = True bp.name = new_name try: bp.full_clean() except ValidationError as e: error_messages.append("Unable to validate and save billing period '{}'. Error: {}".format(bp, str(e))) else: if changed: bp.save() for group in billing_groups: bpcpa_id = 'invoice_amount_group{}{}'.format(group.pk, bp_id) try: bpcpa = BillingPeriodCustomPaymentAmount.objects.get( group=group.pk, period=bp, ) except BillingPeriodCustomPaymentAmount.DoesNotExist: bpcpa = BillingPeriodCustomPaymentAmount() bpcpa.group = group bpcpa.period = bp try: if post['invoice_amount_group{}_{}'.format(group.pk, bp_id)] is None: new_invoice_amount = Decimal('0.00') else: new_invoice_amount = Decimal(post['invoice_amount_group{}_{}'.format(group.pk, bp_id)]) except KeyError as e: alert_messages.append("Field not found saving invoice amount for group '{}' in billing period '{}'. Field was supposed to be '{}'. Error: {}".format(group.name, bp.name, 'invoice_amount_group{}_{}'.format(group.pk, bp_id), str(e))) continue except InvalidOperation as e: error_messages.append("Invalid decimal value found when saving invoice amount for group '{}' in billing period '{}'. Please check it and fix it. Error: {}".format(group.name, bp.name, 'invoice_amount_group{}_{}'.format(group, bp), str(e))) continue # It has not changed, lets just move on from here... if new_invoice_amount == bpcpa.invoice_amount: continue changed = True bpcpa.invoice_amount = new_invoice_amount try: bpcpa.full_clean() except ValidationError as e: error_messages.append("Unable to validate and save invoice amount for group '{}' in billing period '{}'. Error: {}".format(group.name, bp, str(e))) else: bpcpa.save() if changed: updated_periods.append(bp) elif delete_match: # Delete an EXISTING billing period # But only if there are no invoices attached. # Verify user has access to this billing period bp_pk = delete_match.group(1) try: bp = BillingPeriod.objects.get(pk=bp_pk) except BillingPeriod.DoesNotExist as e: error_messages.append("Not able to find Billing Period with ID #{}. Error: {}".format(bp_pk, str(e))) if bp.league.pk != self.league.pk: error_messages.append("You don't seem to have permission to delete a Billing Period in this form. Not sure how that happened. I can't delete it.") # TODO verify no invoices (haven't dev'd the model yet...) bp.delete() deleted_periods.append(bp) success_message = [] if new_periods: success_message.append("Added {} new billing periods.".format(len(new_periods))) if updated_periods: success_message.append("Updated {} billing periods.".format(len(updated_periods))) if deleted_periods: success_message.append("Deleted {} billing periods.".format(len(deleted_periods))) if success_message: messages.success(request, "<h2>Saved Form</h2><p>{}</p>".format("</p><p>".join(success_message))) print(success_message) if error_messages: messages.error(request, "<h2>Errors</h2><ul><li>{}</li></ul>".format("</li><li>".join(error_messages))) print(error_messages) if alert_messages: messages.warning(request, "<h2>Errors</h2><ul><li>{}</li></ul>".format("</li><li>".join(alert_messages))) print(alert_messages) print(success_message) return HttpResponseRedirect( reverse("registration:event_admin_billing_periods", kwargs={'event_slug': self.event.slug}))
def process_exception(self, request, exception): if isinstance(exception, AdministrativeModelError): messages.error(request, u"Impossível alterar esse elemento.") return redirect(request.META['PATH_INFO'])
def show_chat(request,to): from_user = request.user to_user = get_object_or_404(User,username=to) if from_user==to_user: messages.error(request,_(u'Вы не можете написать сообщение самому себе')) # messages.error(request,_(u'Can not write email to yourself')) return HttpResponseRedirect(request.META['HTTP_REFERER']) #get existed chat chat= Chat.objects.filter(from_user=from_user,to_user=to_user) or Chat.objects.filter(to_user=from_user,from_user=to_user) if chat: chat=chat[0] msgs=None if chat: if chat.from_user==from_user: chat.is_from_user_read=False else: chat.is_to_user_read=False chat.save() msgs= chat.comments.all() msgs=Paginator(msgs,10) try: page = request.GET['page'] except: page = 1 try: msgs = msgs.page(page) except (EmptyPage, InvalidPage): msgs = msgs.page(msgs.num_pages) return render_to_response('cart/message.html',{'chat':chat,'msgs':msgs,'to':to},context_instance=RequestContext(request))