def subscribe_process(request, list_id=None): list_id = list_id or getattr(settings, 'MAILCHIMP_LIST_ID', None) if not list_id: error_msg = 'Missing subscription list ID' else: form = ChumpSubscribeForm(data=request.POST or None) error_msg = 'Invalid entry' if form.is_valid(): try: lst = utils.get_connection().get_list_by_id(list_id) opt = { 'EMAIL': form.cleaned_data['email'], 'NAME': form.cleaned_data['name'], } lst.subscribe(form.cleaned_data['email'], opt) url = request.POST.get('next', DONE_URL) # It worked! if request.is_ajax(): # For ajax, return target URL as plain text return HttpResponse(url, content_type='text/plain') return HttpResponseRedirect(url) except URLError: error_msg = 'Subscription temporarily unavailable' except ChimpyException, e: # Chimpy library appends too much shit after first colon error_msg = unicode(e).split(':')[0]
def list_subscribe(request): form = MailChimpForm(data=request.POST) next_page = request.POST.get('next', '/') if form.is_valid(): chimp_list = utils.get_connection().get_list_by_id( settings.MAILCHIMP_LIST_ID) email = form.cleaned_data['email'] name = form.cleaned_data['name'] if ' ' in name: (fname, lname) = name.split(' ', 1) else: fname = name lname = '' chimp_list.subscribe(email, { 'EMAIL': email, 'FNAME': fname, 'LNAME': lname }) if request.is_ajax(): return HttpResponse(status=200) else: messages.success( request, 'You have been sent a confirmation email. ' 'Please follow the instructions within to confirm ' 'your subscription.') return HttpResponseRedirect(next_page) else: if request.is_ajax(): return HttpResponse(status=400) else: messages.error( request, 'Please fill in your name and a valid ' 'email address.') return HttpResponseRedirect(next_page)
def add_to_mailinglist(self, request, queryset): for item in queryset: list = utils.get_connection().get_list_by_id(item.list) count = 0 false_count = 0 customers = Customer.objects.filter(groups__id=item.group.id) for customer in customers: status = 'Geinteresseerd' if customer.house: if customer.definitive: status = 'Koper' else: status = 'Optant' try: list.subscribe(customer.email, {'EMAIL': customer.email, 'FNAME': customer.first_name, 'LNAME': customer.last_name_prefix + ' ' + customer.last_name, 'STATUS': status}, double_optin=False, update_existing=True) count += 1 except ChimpyException: false_count += 1 else: item.customers.add(customer) plural = '' if count != 1: plural = 's' self.message_user(request, "Successfully added %d/%d customer%s to mailchimp list %s." % ( count, count + false_count, plural, list.name))
def mc(self): try: if not hasattr(self, '_mc'): self._mc = get_connection().get_campaign_by_id(self.campaign_id) return self._mc except: return DeletedCampaign()
def list_subscribe(request): form = MailChimpForm(data=request.POST) next_page = request.POST.get('next', '/') if form.is_valid(): chimp_list = utils.get_connection().get_list_by_id( settings.MAILCHIMP_LIST_ID) email = form.cleaned_data['email'] name = form.cleaned_data['name'] if ' ' in name: (fname, lname) = name.split(' ', 1) else: fname = name lname = '' chimp_list.subscribe(email, {'EMAIL': email, 'FNAME': fname, 'LNAME': lname}) if request.is_ajax(): return HttpResponse(status=200) else: messages.success(request, 'You have been sent a confirmation email. ' 'Please follow the instructions within to confirm ' 'your subscription.') return HttpResponseRedirect(next_page) else: if request.is_ajax(): return HttpResponse(status=400) else: messages.error(request, 'Please fill in your name and a valid ' 'email address.') return HttpResponseRedirect(next_page)
def email_thanks(request): """ Page for thanking the user for signup """ if request.method == "POST": form = NewsSubscribeForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] list_id = 'c0995b6e8f' CACHE_TIMEOUT = 3600 * 24 * 3 mailchimp_list = cache.get(list_id) if mailchimp_list: pass else: connection = mailchimputils.get_connection() mailchimp_list = connection.get_list_by_id(list_id) cache.set(list_id, mailchimp_list, CACHE_TIMEOUT) results = mailchimp_list.subscribe( email, { 'EMAIL': email, 'FNAME': '', 'LNAME': '', 'MMERGE3': '', 'MMERGE4': '', 'MMERGE5': 'www.docker.io/', }, 'html', 'true') intercom_extra = { 'email': email, 'news_signup_at': datetime.now().strftime("%Y-%m-%d"), 'signup_location': "www.docker.io", } return render_to_response('base/email_thanks.html', { 'form': form, 'intercom_extra': intercom_extra }, context_instance=RequestContext(request)) else: # form = NewsSubscribeForm() return render_to_response('base/email_form.html', { 'form': form, }, context_instance=RequestContext(request)) else: form = NewsSubscribeForm() return render_to_response('base/email_form.html', { 'form': form, }, context_instance=RequestContext(request))
def empresa(request): #Formulario de busqueda busquedaF = BusquedaForm() # Formulario de nuevo usuario usuarioF = UserCreationForm() #Formulario de ingreso loginF = LoginForm() #Banners superiores banners = Banner.objects.all().order_by('id') #Ciudades ciudades = Ciudad.objects.all() #Zonas zonas = Zona.objects.all() #Datos de la empresa empresa = Empresa.objects.get(id=1) # Ofertas de los productos ofertas = [] ofertas = Producto.objects.filter(oferta=True).filter(disponible=True).order_by('?') # Direccion para redireccionar al logear. redirect = '/empresa/' # Creando un nuevo usuario if request.method=='POST': usuarioF = UserCreationForm(request.POST) usuarioF.is_afiliado = False if usuarioF.is_valid(): email = usuarioF.cleaned_data['email'] list = utils.get_connection().get_list_by_id(MAILCHIMP_LIST_ID) list.subscribe(email, {'EMAIL': email}) usuario = usuarioF.save() #Agrega la notificacion de la transaccion notificacionUsuario = Notificacion.objects.create(nombre="Nuevo usuario creado", tipo='usuario',id_modelo=usuario.id) return HttpResponseRedirect('/') ctx = { 'BusquedaForm':busquedaF, 'ofertas':ofertas, 'UsuarioForm':usuarioF, 'LoginForm':loginF, 'banners':banners, 'ciudades':ciudades, 'zonas':zonas, 'empresa':empresa, 'redirect':redirect, } return render_to_response('main/empresa/empresa.html', ctx, context_instance=RequestContext(request))
def handle(self, *args, **options): print "Installing webhooks for all lists" c = get_connection() for list in c.lists.values(): print "Checking list %s" % list.name # def add_webhook_if_not_exists(self, url, actions, sources): if list.install_webhook(): print " ok" else: print " ERROR!" print "Done"
def handle(self, *args, **options): print('Installing webhooks for all lists') c = get_connection() for list in list(c.lists.values()): print('Checking list %s' % list.name) # def add_webhook_if_not_exists(self, url, actions, sources): if list.install_webhook(): print(' ok') else: print(' ERROR!') print('Done')
def handle(self, *args, **options): print 'Installing webhooks for all lists' c = get_connection() for list in c.lists.values(): print 'Checking list %s' % list.name # def add_webhook_if_not_exists(self, url, actions, sources): if list.install_webhook(): print ' ok' else: print ' ERROR!' print 'Done'
def handle(self, *args, **options): print 'Installing site segment groups for all lists and all sites' c = get_connection() interests = [] for site in Site.objects.all(): interests.append(site.domain) for list in c.lists.values(): print 'Checking list %s' % list.name list.add_interests_if_not_exist(*interests) print ' ok' print 'Done'
def handle(self, *args, **options): print('Installing webhooks for all lists') c = get_connection() for list in c.lists.values(): print('Checking list {}'.format(list.name)) # def add_webhook_if_not_exists(self, url, actions, sources): if list.install_webhook(): print(' ok') else: print(' ERROR!') print('Done')
def handle(self, *args, **options): if len(args) != 1: print 'You have to specify exactly one argument to this command' return merge = args[0] print 'Adding the merge var `%s` to all lists' % merge c = get_connection() for list in c.lists.values(): print 'Checking list %s' % list.name list.add_merges_if_not_exists(merge) print ' ok' print 'Done'
def handle(self, *args, **options): if len(args) != 1: print('You have to specify exactly one argument to this command') return merge = args[0] print('Adding the merge var `{}` to all lists'.format(merge)) c = get_connection() for list in c.lists.values(): print('Checking list {}'.format(list.name)) list.add_merges_if_not_exists(merge) print(' ok') print('Done')
def send(self): """ send (schedule) this queued object """ # check lock if self.locked: return False # aquire lock self.locked = True self.save() # get connection and send the mails c = get_connection() tpl = c.get_template_by_id(self.template_id) content_data = dict([ (str(k), v) for k, v in simplejson.loads(self.contents).items() ]) built_template = tpl.build(**content_data) tracking = { 'opens': self.tracking_opens, 'html_clicks': self.tracking_html_clicks, 'text_clicks': self.tracking_text_clicks } if self.google_analytics: analytics = {'google': self.google_analytics} else: analytics = {} segment_opts = { 'match': 'all' if self.segment_options_all else 'any', 'conditions': simplejson.loads(self.segment_options_conditions) } type_opts = simplejson.loads(self.type_opts) title = self.title or self.subject camp = c.create_campaign(self.campaign_type, c.get_list_by_id(self.list_id), built_template, self.subject, self.from_email, self.from_name, self.to_email, self.folder_id, tracking, title, self.authenticate, analytics, self.auto_footer, self.generate_text, self.auto_tweet, segment_opts, type_opts) if camp.send_now_async(): self.delete() kwargs = {} if self.content_type and self.object_id: kwargs['content_type'] = self.content_type kwargs['object_id'] = self.object_id if self.extra_info: kwargs['extra_info'] = simplejson.loads(self.extra_info) return Campaign.objects.create(camp.id, segment_opts, **kwargs) # release lock if failed self.locked = False self.save() return False
def create(self, campaign_id, segment_opts, content_type=None, object_id=None, extra_info=[]): con = get_connection() camp = con.get_campaign_by_id(campaign_id) extra_info = simplejson.dumps(extra_info) obj = self.model(content=camp.content, campaign_id=campaign_id, name=camp.title, content_type=content_type, object_id=object_id, extra_info=extra_info) obj.save() segment_opts = dict([(str(k), v) for k,v in segment_opts.items()]) for email in camp.list.filter_members(segment_opts): Reciever.objects.create(campaign=obj, email=email) return obj
def create(self, campaign_id, segment_opts, content_type=None, object_id=None, extra_info=[]): con = get_connection() camp = con.get_campaign_by_id(campaign_id) extra_info = json.dumps(extra_info) obj = self.model(content=camp.content, campaign_id=campaign_id, name=camp.title, content_type=content_type, object_id=object_id, extra_info=extra_info) obj.save() segment_opts = dict([(str(k), v) for k,v in segment_opts.items()]) for email in camp.list.filter_members(segment_opts): Reciever.objects.create(campaign=obj, email=email) return obj
def email_thanks(request): """ Page for thanking the user for signup """ if request.method == "POST": form = NewsSubscribeForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] list_id = "c0995b6e8f" CACHE_TIMEOUT = 3600 * 24 * 3 mailchimp_list = cache.get(list_id) if mailchimp_list: pass else: connection = mailchimputils.get_connection() mailchimp_list = connection.get_list_by_id(list_id) cache.set(list_id, mailchimp_list, CACHE_TIMEOUT) results = mailchimp_list.subscribe( email, {"EMAIL": email, "FNAME": "", "LNAME": "", "MMERGE3": "", "MMERGE4": "", "MMERGE5": "www.docker.io/"}, "html", "true", ) intercom_extra = { "email": email, "news_signup_at": datetime.now().strftime("%Y-%m-%d"), "signup_location": "www.docker.io", } return render_to_response( "base/email_thanks.html", {"form": form, "intercom_extra": intercom_extra}, context_instance=RequestContext(request), ) else: # form = NewsSubscribeForm() return render_to_response("base/email_form.html", {"form": form}, context_instance=RequestContext(request)) else: form = NewsSubscribeForm() return render_to_response("base/email_form.html", {"form": form}, context_instance=RequestContext(request))
def send(self): """ send (schedule) this queued object """ # check lock if self.locked: return False # aquire lock self.locked = True self.save() # get connection and send the mails c = get_connection() tpl = c.get_template_by_id(self.template_id) content_data = dict([(str(k), v) for k, v in simplejson.loads(self.contents).items()]) built_template = tpl.build(**content_data) tracking = {'opens': self.tracking_opens, 'html_clicks': self.tracking_html_clicks, 'text_clicks': self.tracking_text_clicks} if self.google_analytics: analytics = {'google': self.google_analytics} else: analytics = {} segment_opts = { 'match': 'all' if self.segment_options_all else 'any', 'conditions': simplejson.loads(self.segment_options_conditions) } type_opts = simplejson.loads(self.type_opts) title = self.title or self.subject camp = c.create_campaign( self.campaign_type, c.get_list_by_id(self.list_id), built_template, self.subject, self.from_email, self.from_name, self.to_email, self.folder_id, tracking, title, self.authenticate, analytics, self.auto_footer, self.generate_text, self.auto_tweet, segment_opts, type_opts ) if camp.send_now_async(): self.delete() kwargs = {} if self.content_type and self.object_id: kwargs['content_type'] = self.content_type kwargs['object_id'] = self.object_id if self.extra_info: kwargs['extra_info'] = simplejson.loads(self.extra_info) return Campaign.objects.create(camp.id, segment_opts, **kwargs) # release lock if failed self.locked = False self.save() return False
def email_thanks(request): """ Page for thanking the user for signup """ if request.method == "POST": form = NewsSubscribeForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] list = mailchimputils.get_connection().get_list_by_id('c0995b6e8f') results = list.subscribe( '*****@*****.**', { 'EMAIL': '*****@*****.**', 'FNAME': '', 'LNAME': '', 'MMERGE3': '', 'MMERGE4': '', 'MMERGE5': 'www.docker.io/', }, 'html', 'true') intercom_extra = { 'email': "*****@*****.**", 'news_signup_at': datetime.now().strftime("%Y-%m-%d"), # 'created_at': datetime.now().strftime("%s"), # 'github_name': 'dhrp2', } return render_to_response('base/email_thanks.html', { 'form': form, 'intercom_extra': intercom_extra }, context_instance=RequestContext(request)) else: # form = NewsSubscribeForm() return render_to_response('base/email_form.html', { 'form': form, }, context_instance=RequestContext(request)) return render_to_response("homepage.md", { "form": form, }, context_instance=RequestContext(request))
def email_thanks(request): """ Page for thanking the user for signup """ if request.method == "POST": form = NewsSubscribeForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] list = mailchimputils.get_connection().get_list_by_id('c0995b6e8f') results = list.subscribe( '*****@*****.**', { 'EMAIL': '*****@*****.**', 'FNAME': '', 'LNAME': '', 'MMERGE3': '', 'MMERGE4': '', 'MMERGE5': 'www.docker.io/', }, 'html', 'true' ) intercom_extra = { 'email': "*****@*****.**", 'news_signup_at': datetime.now().strftime("%Y-%m-%d"), # 'created_at': datetime.now().strftime("%s"), # 'github_name': 'dhrp2', } return render_to_response('base/email_thanks.html', { 'form': form, 'intercom_extra': intercom_extra }, context_instance = RequestContext(request)) else: form = NewsSubscribeForm() return render_to_response("homepage.md", { "form": form, }, context_instance=RequestContext(request))
def email_thanks(request): """ Page for thanking the user for signup """ if request.method == "POST": form = NewsSubscribeForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] list = mailchimputils.get_connection().get_list_by_id("c0995b6e8f") results = list.subscribe( "*****@*****.**", { "EMAIL": "*****@*****.**", "FNAME": "", "LNAME": "", "MMERGE3": "", "MMERGE4": "", "MMERGE5": "www.docker.io/", }, "html", "true", ) intercom_extra = { "email": "*****@*****.**", "news_signup_at": datetime.now().strftime("%Y-%m-%d"), # 'created_at': datetime.now().strftime("%s"), # 'github_name': 'dhrp2', } return render_to_response( "base/email_thanks.html", {"form": form, "intercom_extra": intercom_extra}, context_instance=RequestContext(request), ) else: # form = NewsSubscribeForm() return render_to_response("base/email_form.html", {"form": form}, context_instance=RequestContext(request)) return render_to_response("homepage.md", {"form": form}, context_instance=RequestContext(request))
def ajax_registar_suscripcion(request): if request.is_ajax(): if request.method == 'POST': correo = SuscripcionForm(request.POST) if correo.is_valid(): correo.save() msg = EmailMessage(subject="Bienvenido al e-comerce", from_email="LA empresa <*****@*****.**>", to=[request.POST['email']]) msg.template_name = "Nuevo" msg.template_content = { "contenido" : "<h1>HOLAAAAAAAAAAAA Bienvenido a este e-comerce</h1>" } msg.send() lista = utils.get_connection().get_list_by_id('5a8860d1e1') lista.subscribe(request.POST['email'], {'EMAIL': request.POST['email'], 'FNAME': request.POST['nombre']}) dato = 1 else: dato = 2 else: dato = 0 return HttpResponse(dato)
def connection(self): return get_connection()
def func(request, page): MAILCHIMP_LIST_ID = '07c04a0064' try: list = utils.get_connection().get_list_by_id(MAILCHIMP_LIST_ID) except Exception, e: stdout.write("Error getting mailchimp list: {0}".format(e))
def get_list(self): return get_connection().lists[self.list_id]
def pagar(request, id_producto): #Formulario de busqueda busquedaF = BusquedaForm() # Formulario de nuevo usuario usuarioF = UserCreationForm() #Formulario de ingreso loginF = LoginForm() #Banners superiores banners = Banner.objects.all().order_by('id') # Formulario de contacto contactoF = ContactoForm() #Ciudades ciudades = Ciudad.objects.all() #Zonas zonas = Zona.objects.all() # Ofertas de los productos ofertas = [] ofertas = Producto.objects.filter(oferta=True).filter(disponible=True).order_by('?') # Direccion para redireccionar al logear. redirect = request.path producto = Producto.objects.get(id=id_producto) boton = '' precio = 0 # Creando un nuevo usuario if request.method=='POST': usuarioF = UserCreationForm(request.POST) usuarioF.is_afiliado = False if usuarioF.is_valid(): email = usuarioF.cleaned_data['email'] list = utils.get_connection().get_list_by_id(MAILCHIMP_LIST_ID) list.subscribe(email, {'EMAIL': email}) usuarioF.save() #Agrega la notificacion de la transaccion notificacionUsuario = Notificacion.objects.create(nombre="Nuevo usuario creado", tipo='usuario',id_modelo=usuarioF.id) return HttpResponseRedirect('/') #Registro del pago. nombre = producto.titulo razon = producto fecha = datetime.datetime.now() usuario = request.user alquilerF = AlquilerForm(request.POST) ventaF = VentaForm(request.POST) agotado = False botonMp = True if alquilerF.is_valid(): print 'Here!' precio = alquilerF.cleaned_data['total'] dias = alquilerF.cleaned_data['dias'] total = alquilerF.cleaned_data['total'] cantidad = alquilerF.cleaned_data['cantidad'] acepto = alquilerF.cleaned_data['clausulas'] # Verifica si el producto esta agotado if producto.cantidad == 0: agotado = True botonMp = False else: pagoAlquiler = PagoAlquiler.objects.create(producto=razon,monto=precio,dias=dias, fecha=fecha,usuario=usuario,verificado=False, cantidad=cantidad,aceptado=acepto) producto.cantidad = producto.cantidad - cantidad #Agrega la notificacion de la transaccion notificacionAlquiler = Notificacion.objects.create(nombre="Nuevo alquiler realizado", tipo='alquiler',id_modelo=producto.id) #Verifica la cantidad de productos y envia email dependiendo de si se agoto if producto.cantidad == 0: producto.disponible = False email_agotado(request, producto) producto.save() email_alquiler(request, usuario.nombre, usuario.apellido, usuario.telefono, usuario.email, nombre, dias, cantidad) if total > 100000.00: botonMp = False elif ventaF.is_valid(): precio = ventaF.cleaned_data['total'] cantidad = ventaF.cleaned_data['cantidad'] acepto = ventaF.cleaned_data['clausulas'] # Verifica si el producto esta agotado if producto.cantidad == 0: agotado = True botonMp = False else: pagoVenta = PagoVenta.objects.create(producto=razon,monto=precio,fecha=fecha, usuario=usuario,verificado=False,cantidad=cantidad,aceptado=acepto) producto.cantidad = producto.cantidad - cantidad #Agrega la notificacion de la transaccion notificacionVenta = Notificacion.objects.create(nombre="Nueva venta realizada", tipo='venta',id_modelo=producto.id) #Verifica la cantidad de productos y envia email dependiendo de si se agoto if producto.cantidad == 0: producto.disponible = False email_agotado(request, producto) producto.save() email_venta(request, usuario.nombre, usuario.apellido, usuario.telefono, usuario.email, nombre, cantidad) if precio > 100000.00: botonMp = False #Generacion de boton de mercadopago if botonMp: boton = mercadopago(request, nombre, float(precio)) #Contactos de alquiherramientas contactos = Contactos.objects.get(id=1) ctx = { 'BusquedaForm':busquedaF, 'ofertas':ofertas, 'producto': producto, 'UsuarioForm':usuarioF, 'LoginForm':loginF, 'banners':banners, 'ciudades':ciudades, 'zonas':zonas, 'contactoF': contactoF, 'boton_mp': boton, 'redirect':redirect, 'agotado':agotado, 'botonMp':botonMp, 'contactos':contactos, } return render_to_response('main/productos/pago.html', ctx, context_instance=RequestContext(request))
def productos(request, palabra): #Formulario de busqueda busquedaF = BusquedaForm() #Formulario de nuevo usuario usuarioF = UserCreationForm() #Formulario de ingreso loginF = LoginForm() #Banners superiores banners = Banner.objects.all().order_by('id') #Ciudades ciudades = {} #Zonas zonas = {} # Ofertas de los productos ofertas = [] ofertas = Producto.objects.filter(oferta=True).filter(disponible=True).order_by('?') # Direccion para redireccionar al logear. redirect = request.path #productos que se ofertan if palabra == 'alquiler': productos = Alquiler.objects.filter(disponible=True).order_by('fecha_producto') else: productos = Venta.objects.filter(disponible=True).order_by('fecha_producto') # Creando un nuevo usuario if request.method=='POST': usuarioF = UserCreationForm(request.POST) usuarioF.is_afiliado = False if usuarioF.is_valid(): email = usuarioF.cleaned_data['email'] list = utils.get_connection().get_list_by_id(MAILCHIMP_LIST_ID) list.subscribe(email, {'EMAIL': email}) usuario = usuarioF.save() #Agrega la notificacion de la transaccion notificacionUsuario = Notificacion.objects.create(nombre="Nuevo usuario creado", tipo='usuario',id_modelo=usuario.id) return HttpResponseRedirect('/') #Busqueda de propiedades en el pais actual paginator = Paginator(productos, 6) page = request.GET.get('page') try: productos = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. productos = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. productos = paginator.page(paginator.num_pages) #Preparar el objeto Json de las ciudades for estado in Estado.objects.all(): ciudades[estado.id] = dict(Ciudad.objects.filter(estado=estado).values_list('id', 'nombre')) ciudades = json.dumps(ciudades) #Preparar el objeto Json de las zonas for ciudad in Ciudad.objects.all(): zona = dict(Zona.objects.filter(ciudad__id=ciudad.id).values_list('id', 'nombre')) if zona != {}: zonas[ciudad.id] = zona zonas = json.dumps(zonas) ctx = { 'BusquedaForm':busquedaF, 'ofertas':ofertas, 'productos':productos, 'UsuarioForm':usuarioF, 'LoginForm':loginF, 'banners':banners, 'ciudades':ciudades, 'zonas':zonas, 'palabra':palabra, 'redirect':redirect, } return render_to_response('main/productos/productos.html', ctx, context_instance=RequestContext(request))
def email_thanks(request): """ Page for thanking the user for signup """ if request.method == "POST": form = NewsSubscribeForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] list_id = 'c0995b6e8f' CACHE_TIMEOUT = 3600 * 24 * 3 # 3 days # we use local memory cache because the db cache fails to pickle # the mailchimp_list object cache = get_cache('LocMemCache') mailchimp_list = cache.get(list_id) if mailchimp_list: pass else: connection = mailchimputils.get_connection() mailchimp_list = connection.get_list_by_id(list_id) cache.set(list_id, mailchimp_list, CACHE_TIMEOUT) extra_text = None try: results = mailchimp_list.subscribe( email, { 'EMAIL': email, 'FNAME': '', 'LNAME': '', 'MMERGE3': '', 'MMERGE4': '', 'MMERGE5': 'www.docker.io/', }, 'html', 'true') except ChimpyException as error: extra_text = "You are already subscribed to this list" print error pass intercom_extra = { 'email': email, 'news_signup_at': datetime.now().strftime("%Y-%m-%d"), 'signup_location': "www.docker.io", } return render_to_response('base/email_thanks.html', { 'form': form, 'intercom_extra': intercom_extra, 'extra_text': extra_text }, context_instance=RequestContext(request)) else: # form = NewsSubscribeForm() return render_to_response('base/email_form.html', { 'form': form, }, context_instance=RequestContext(request)) else: form = NewsSubscribeForm() return render_to_response('base/email_form.html', { 'form': form, }, context_instance=RequestContext(request))
def producto(request, id_producto): #Formulario de busqueda busquedaF = BusquedaForm() #Formulario de nuevo usuario usuarioF = UserCreationForm() #Formulario de ingreso loginF = LoginForm() #Banners superiores banners = Banner.objects.all().order_by('id') # Formulario de contacto contactoF = ContactoForm() #Ciudades ciudades = Ciudad.objects.all() #Zonas zonas = Zona.objects.all() #Ofertas de los productos ofertas = [] ofertas = Producto.objects.filter(oferta=True).filter(disponible=True).order_by('?') #Direccion para redireccionar al logear. redirect = request.path producto = Producto.objects.get(id=id_producto) cantidad = producto.cantidad #Datos iniciales de formularios de venta y alquiler dataA = {} dataV = {} ventaF = VentaForm() alquilerF = AlquilerForm() # Formularios de compra o alquiler con data inicial. try: dataA = { 'precio': producto.alquiler.precio, 'dias':1, 'cantidad':1, 'garantia': producto.alquiler.precio, 'total':producto.alquiler.precio, 'clausulas':False } except: dataV = { 'precio': producto.venta.precio, 'cantidad':1, 'total': producto.venta.precio } #Se verifica que sea alquiler o venta para inicializar el formulario if dataA != {}: alquilerF = AlquilerForm(initial=dataA) alquilerF.fields['cantidad'] = forms.IntegerField(required=True,min_value=1,max_value=producto.cantidad) try: clausula = Clausula.objects.get(tipo='alquiler') except: clausula = '' elif dataV != {}: ventaF = VentaForm(initial=dataV) ventaF.fields['cantidad'] = forms.IntegerField(required=True,min_value=1,max_value=producto.cantidad) try: clausula = Clausula.objects.get(tipo='venta') except: clausula = '' # Creando un nuevo usuario if request.method=='POST': nombre = producto.titulo usuarioF = UserCreationForm(request.POST) usuarioF.is_afiliado = False contactoF = ContactoForm(request.POST) if usuarioF.is_valid(): email = usuarioF.cleaned_data['email'] list = utils.get_connection().get_list_by_id(MAILCHIMP_LIST_ID) list.subscribe(email, {'EMAIL': email}) usuario = usuarioF.save() #Agrega la notificacion de la transaccion notificacionUsuario = Notificacion.objects.create(nombre="Nuevo usuario creado", tipo='usuario',id_modelo=usuario.id) return HttpResponseRedirect('/') if contactoF.is_valid(): contact_email_producto(request, contactoF, nombre, id_producto) retorno = '/productos/'+str(id_producto)+'/' return HttpResponseRedirect(retorno) # Crear el slider con las imagenes del producto imagenes = [] imagenes = ImagenProducto.objects.filter(Producto=id_producto).order_by('id') imagen = producto.imagen ctx = { 'BusquedaForm':busquedaF, 'LoginForm':loginF, 'banners':banners, 'UsuarioForm':usuarioF, 'ofertas':ofertas, 'producto':producto, 'alquilerF':alquilerF, 'ventaF':ventaF, 'ciudades':ciudades, 'zonas':zonas, 'contactoF':contactoF, 'imagen':imagen, 'imagenes':imagenes, 'redirect':redirect, 'clausula':clausula, } return render_to_response('main/productos/producto.html', ctx, context_instance=RequestContext(request))
def inicio(request): #Formulario de busqueda busquedaF = BusquedaForm() #Formulario de nuevo usuario usuarioF = UserCreationForm() #Formulario de ingreso loginF = LoginForm() #Banners superiores banners = Banner.objects.all().order_by('id') # Ofertas de los productos ofertas = [] ofertas = Producto.objects.filter(oferta=True).filter(disponible=True).order_by('?') #Ciudades ciudades = {} #Zonas zonas = {} # Direccion para redireccionar al logear. redirect = '/' #Productos que se ofertan productos = Producto.objects.filter(disponible=True).order_by('fecha_producto') productos_list = productos #Caso que se realizo una busqueda if request.GET: busquedaF = BusquedaForm(request.GET) #Caso para el buscador de herramientas if busquedaF.is_valid(): tipo = busquedaF.cleaned_data['tipo'] categoria = busquedaF.cleaned_data['categoria'] marca = busquedaF.cleaned_data['marca'] estado = busquedaF.cleaned_data['estado'] ano = busquedaF.cleaned_data['ano'] precio = busquedaF.cleaned_data['precio'] precio = precio.split('-', 2) #Precios en el rango que se pide if len(precio) > 1: precio_menor = precio[0] precio_mayor = precio[1] else: precio_menor = 0 precio_mayor = 10000000000000000 #Verificacion de campos if tipo != '' or categoria != None or marca != None or estado != None or ano != None or len(precio) > 1: #Verificacion de string vacio if tipo == '': tipo = None #Campos a buscar fields_list = [] fields_list.append('herramienta') fields_list.append('herramienta') fields_list.append('herramienta') fields_list.append('direccion') if tipo == 'venta': fields_list.append('precio') elif tipo == 'alquiler': fields_list.append('precio') #Comparadores para buscar types_list=[] types_list.append('categoria__nombre__exact') types_list.append('marca__nombre__exact') types_list.append('ano__exact') types_list.append('estado__nombre__exact') types_list.append('range') #Valores a buscar values_list=[] values_list.append(categoria) values_list.append(marca) values_list.append(ano) values_list.append(estado) values_list.append((precio_menor, precio_mayor)) operator = 'and' if tipo != None: if tipo == 'alquiler': productos_list = dynamic_query(Alquiler, fields_list, types_list, values_list, operator) if productos_list == {}: productos_list = Alquiler.objects.all().order_by('fecha_producto') else: productos_list = dynamic_query(Venta, fields_list, types_list, values_list, operator) if productos_list == {}: productos_list = Venta.objects.all().order_by('fecha_producto') else: productos_list = dynamic_query(Producto, fields_list, types_list, values_list, operator) #Paginacion y busqueda productos_list = tuple(productos_list) paginator = Paginator(productos_list, 6) page = request.GET.get('page') #Busqueda con paginacion query = request.GET.copy() if query.has_key('page'): del query['page'] try: productos = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. productos = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. productos = paginator.page(paginator.num_pages) # Creando un nuevo usuario if request.method=='POST': usuarioF = UserCreationForm(request.POST) usuarioF.is_afiliado = False if usuarioF.is_valid(): email = usuarioF.cleaned_data['email'] list = utils.get_connection().get_list_by_id(MAILCHIMP_LIST_ID) list.subscribe(email, {'EMAIL': email}) usuario = usuarioF.save() #Agrega la notificacion de la transaccion notificacionUsuario = Notificacion.objects.create(nombre="Nuevo usuario creado", tipo='usuario',id_modelo=usuario.id) return HttpResponseRedirect('/') elif loginF.is_valid(): return HttpResponseRedirect('/login/') #Preparar el objeto Json de las ciudades for estado in Estado.objects.all(): ciudades[estado.id] = dict(Ciudad.objects.filter(estado=estado).values_list('id', 'nombre')) ciudades = json.dumps(ciudades) #Preparar el objeto Json de las zonas for ciudad in Ciudad.objects.all(): zona = dict(Zona.objects.filter(ciudad__id=ciudad.id).values_list('id', 'nombre')) if zona != {}: zonas[ciudad.id] = zona zonas = json.dumps(zonas) ctx = { 'BusquedaForm':busquedaF, 'ofertas':ofertas, 'productos':productos, 'UsuarioForm':usuarioF, 'LoginForm':loginF, 'banners':banners, 'ciudades':ciudades, 'zonas':zonas, 'redirect':redirect, 'query':query, } return render_to_response('main/inicio/inicio.html', ctx, context_instance=RequestContext(request))
def email_thanks(request): """ Page for thanking the user for signup """ if request.method == "POST": form = NewsSubscribeForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] list_id = 'c0995b6e8f' CACHE_TIMEOUT = 3600 * 24 * 3 mailchimp_list = cache.get(list_id) if mailchimp_list: pass else: connection = mailchimputils.get_connection() mailchimp_list = connection.get_list_by_id(list_id) cache.set(list_id, mailchimp_list, CACHE_TIMEOUT) extra_text = None try: results = mailchimp_list.subscribe( email, { 'EMAIL': email, 'FNAME': '', 'LNAME': '', 'MMERGE3': '', 'MMERGE4': '', 'MMERGE5': 'www.docker.io/', }, 'html', 'true' ) except ChimpyException as error: extra_text = "You are already subscribed to this list" print error pass intercom_extra = { 'email': email, 'news_signup_at': datetime.now().strftime("%Y-%m-%d"), 'signup_location': "www.docker.io", } return render_to_response('base/email_thanks.html', { 'form': form, 'intercom_extra': intercom_extra, 'extra_text': extra_text }, context_instance=RequestContext(request)) else: # form = NewsSubscribeForm() return render_to_response('base/email_form.html', { 'form': form, }, context_instance=RequestContext(request)) else: form = NewsSubscribeForm() return render_to_response('base/email_form.html', { 'form': form, }, context_instance=RequestContext(request))