def __init__(self, *args, **kwargs): if not kwargs.get('slug') and 'slug' in self._meta.get_all_field_names(): if kwargs.get('title'): kwargs['slug'] = smart_slugify(kwargs['title'], lower_case=True) elif kwargs.get('name'): kwargs['slug'] = smart_slugify(kwargs['name'], lower_case=True) elif kwargs: import warnings warnings.warn("Unable to automagically set slug (%s)" % \ self._meta.get_all_field_names()) super(Model, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): if not kwargs.get('slug') and 'slug' in self._meta.get_all_field_names(): if kwargs.get('title'): kwargs['slug'] = smart_slugify(kwargs['title'], lower_case=True) elif kwargs.get('name'): kwargs['slug'] = smart_slugify(kwargs['name'], lower_case=True) elif kwargs: import warnings warnings.warn("Unable to automagically set slug (%s)" % \ self._meta.get_all_field_names()) super(AutoSlugModel, self).__init__(*args, **kwargs)
def generate_map_2010(request, date=None): from slugify import smart_slugify source_map = render_to_string('constituency-map-2010.svg',{}) year = settings.CONSTITUENCY_YEAR levels = {0:'level1', 0.1:'level2', 0.2:'level3', 0.3:'level4', 0.4:'level5', 0.5:'level6', 0.6:'level7', 0.7:'level8', 0.8:'level9', 0.9:'level10'} level_keys = levels.keys() level_keys.sort() lines = [] r = re.compile(r" id=\"([^\"]+)\" ") for line in source_map.splitlines(): result = r.search(line) if result: slug = smart_slugify(result.groups(1)[0].lower()) constituency = None if slug == "orkney-shetland-box": pass else: try: constituency = Constituency.objects.get(slug=slug,year=year) except Constituency.DoesNotExist: slug = slug.replace("-and", "") try: constituency = Constituency.objects.get(slug=slug,year=year) except Constituency.DoesNotExist: pass if constituency: level = 'none' the_count = constituency.customuser_set.filter(is_active=True) if date: the_count = the_count.filter(date_joined__lt=date) score = min(float(the_count.count())/10, 1) for l in takewhile(lambda x: score > x, level_keys): level = levels[l] line = line.replace('class="', 'class="%s ' % level) lines.append(line) return HttpResponse("\n".join(lines), mimetype="image/svg+xml")
def create_narrative(request): if 'title' in request.POST: title = request.POST['title'] narrative = Narrative.objects.create(title=title, slug=smart_slugify(title)) term = title tags = 'tone/news' search = GuardianSearch.objects.create(narrative=narrative, term=term, tags=tags) flush_narrative(request, narrative.slug) return HttpResponseRedirect(reverse('narrative_slug', kwargs={'slug': narrative.slug})) else: return render_with_context(request, 'narrative_create.html', {},)
def handle(self, *args, **options): if not args or (args and args[0] not in ('load')): raise CommandError("USAGE: ./manage.py %s load" % \ os.path.basename(__file__).split('.')[0]) transaction.enter_transaction_management() transaction.managed(True) year = CONSTITUENCY_YEAR.strftime("%Y") constituencies = twfy.getConstituencies(date=year) for c in constituencies: item = models.Constituency(name=c, year=CONSTITUENCY_YEAR) item.slug = smart_slugify(item.name, manager=models.Constituency.objects, lower_case=True) if not ("silent" in options) or options["silent"] == False: print "Loading %s <%s>" % (item.name, item.slug) item.save() transaction.commit()
def handle(self, *args, **options): if not args or (args and args[0] not in ('load')): raise CommandError("USAGE: ./manage.py %s load" % \ os.path.basename(__file__).split('.')[0]) transaction.enter_transaction_management() transaction.managed(True) year = CONSTITUENCY_YEAR.strftime("%Y") constituencies = twfy.getConstituencies(date=year) for c in constituencies: item = models.Constituency(name=c, year=CONSTITUENCY_YEAR) item.slug = smart_slugify(item.name, manager=models.Constituency.objects, lower_case=True) if not ("silent" in options) or options["silent"] == False: print "Loading %s <%s>" % (item.name, item.slug) item.save() transaction.commit()
def order_step_one(request, basket=None): try: basket = Basket.objects.get(id=request.session["BASKET_ID"]) except: pass try: order = get_object_or_404(Order, id=request.session["ORDER_ID"]) email = order.owner.email house_name_number = order.address.house_name_number address_line_1 = order.address.address_line_1 address_line_2 = order.address.address_line_2 town_city = order.address.town_city postcode = order.address.postcode province_state = order.address.province_state country = order.address.country first_name = order.owner.first_name last_name = order.owner.last_name except: order = None if not basket and not order: problem = _("You don't have any items in your basket, so you can't process an order!") return _render(request, "shop/order-problem.html", locals()) if request.method == "POST": post_values = request.POST.copy() initial_values = ( _("First name"), _("Last name"), _("Email address"), _("Your address..."), _(" ...address continued (optional)"), _("Town or city"), _("State"), _("Post / ZIP code"), _("invalid"), ) for k, v in post_values.iteritems(): if v in initial_values: del post_values[k] form = OrderStepOneForm(post_values) if form.is_valid(): # FIRST, GET THE USER if request.user.is_authenticated(): user = request.user else: try: user = User.objects.filter(email=form.cleaned_data["email"])[0] except IndexError: creation_args = { "username": form.cleaned_data["email"], "email": form.cleaned_data["email"], "password": uuid.uuid1().hex, } user = User.objects.create(**creation_args) user.first_name = form.cleaned_data["first_name"] user.last_name = form.cleaned_data["last_name"] user.save() try: shopper = get_object_or_404(Shopper, user=user) except MultipleObjectsReturned: shopper = Shopper.objects.filter(user=user)[0] except: creation_args = { "user": user, "email": user.email, "first_name": user.first_name, "last_name": user.last_name, "slug": smart_slugify( "".join((form.cleaned_data["first_name"], form.cleaned_data["last_name"])), lower_case=True ), "language": get_language(), } shopper = Shopper.objects.create(**creation_args) # CREATE AN ADDRESS OBJECT address = Address.objects.create( owner=shopper, house_name_number=form.cleaned_data["house_name_number"], address_line_1=form.cleaned_data["address_line_1"], address_line_2=form.cleaned_data["address_line_2"], town_city=form.cleaned_data["town_city"], postcode=form.cleaned_data["postcode"], country=form.cleaned_data["country"], ) try: address.province_state = form.cleaned_data["province_state"] address.save() except: pass # if they agree to get an email newsletter if form.cleaned_data["newsletter"] == True: from signals import update_mailing_list update_mailing_list.send( sender=update_mailing_list, email_address=form.cleaned_data["email"], lang_code=get_language() ) # CREATE OR FIND THE ORDER try: order = get_object_or_404(Order, id=request.session["ORDER_ID"]) if not order.hashkey: order.hashkey = uuid.uuid1().hex order.save() except: creation_args = { "date_confirmed": datetime.now(), "address": address, "owner": shopper, "status": Order.STATUS_CREATED_NOT_PAID, "invoice_id": "TEMP", "hashkey": uuid.uuid1().hex, } order = Order.objects.create(**creation_args) order.save() # need to save it first, then give it an ID if settings.AFFILIATE_SESSION_KEY in request.session: order.invoice_id = "TEA-00%sA" % (order.id) order.affiliate_referrer = request.session[settings.AFFILIATE_SESSION_KEY] else: order.invoice_id = "TEA-00%s" % (order.id) # DO THEY HAVE A VALID DISCOUNT CODE? try: discount = get_object_or_404(Discount, pk=request.session["DISCOUNT_ID"]) order.discount = discount except: pass # UPDATE ORDER WITH THE BASKET ITEMS basket_items = BasketItem.objects.filter(basket=basket) for item in basket_items: order.items.add(item) order.save() request.session["ORDER_ID"] = order.id # FINALLY! WE'RE DONE return HttpResponseRedirect(reverse("order_confirm")) # IF THE FORM HAS ERRORS: else: # LOAD EXISTING DATA email = request.POST["email"] house_name_number = request.POST["house_name_number"] address_line_1 = request.POST["address_line_1"] address_line_2 = request.POST["address_line_2"] town_city = request.POST["town_city"] postcode = request.POST["postcode"] country = request.POST["country"] first_name = request.POST["first_name"] last_name = request.POST["last_name"] try: province_state = request.POST["province_state"] except: pass form = OrderStepOneForm(post_values) else: form = OrderStepOneForm() return _render(request, "shop/forms/order_step_one.html", locals())
def handle(self, *args, **options): if not args or (args and args[0] not in ('load', 'update')): raise CommandError("USAGE: ./manage.py %s load" % \ os.path.basename(__file__).split('.')[0]) transaction.enter_transaction_management() transaction.managed(True) year = CONSTITUENCY_YEAR.strftime("%Y") constituencies = twfy.getConstituencies(date=year) if args[0] == 'load': for c in constituencies: try: lat, lon = (c['centre_lat'], c['centre_lon']) except KeyError: # this happens for Northern Ireland - no geodata available lat, lon = (None, None) # XXX new "api" inconsistuency name = c.get('name', c.get('Name', '')) item = models.Constituency(name=name, year=CONSTITUENCY_YEAR, lat=lat, lon=lon) item.slug = smart_slugify(item.name, manager=models.Constituency.objects, lower_case=True) if not ("silent" in options) or options["silent"] == False: print "Loading %s <%s>" % (item.name, item.slug) item.save() else: geometries = twfy.getGeometry() for c in constituencies: name = c.get('name', c.get('Name', '')) item = models.Constituency.objects.\ filter(name=name, year=CONSTITUENCY_YEAR).get() c.update(geometries[name]) try: item.lat = c['centre_lat'] item.lon = c['centre_lon'] except KeyError: # this happens for Northern Ireland continue #if not ("silent" in options) or options["silent"] == False: # print "Updating %s (%d, %d)" % \ # (item.name, item.lat, item.lon) item.save() for user in models.CustomUser.objects.all(): constituency_name = twfy.getConstituency(user.postcode) try: constituency = models.Constituency.objects.all()\ .filter(name=constituency_name)\ .filter(year=CONSTITUENCY_YEAR).get() except models.Constituency.DoesNotExist: print "error:", user continue user.constituencies.add(constituency) user.save() prior = user.constituencies.filter(year__lt=CONSTITUENCY_YEAR) prior = prior.order_by('signup_customuser_constituencies.id') if len(prior) > 1: print user, "has extra constituencies" for extra in prior[1:]: constituency_set = models.Constituency.objects\ .filter(year=CONSTITUENCY_YEAR) distances = [] for c in constituency_set: if not c.lat or not extra.lat: continue distance = geo.haversine((c.lat, c.lon), (extra.lat, extra.lon)) distances.append((c, distance)) nearest = sorted(distances, key=lambda x: x[1]) if nearest: constituency = nearest[0][0] print " old", extra, "new", constituency user.constituencies.add(constituency) user.save() else: print " couldn't work out new additionals for",user, extra #if not ("silent" in options) or options["silent"] == False: # print "reset home constituency for %s" % user transaction.commit()
def handle(self, *args, **options): if not args or (args and args[0] not in ('rollback', 'commit')): raise CommandError("USAGE: ./manage.py %s rollback|commit" % \ os.path.basename(__file__).split('.')[0]) rollback = args[0] == 'rollback' transaction.enter_transaction_management() transaction.managed(True) for item in models.SectorTag.objects.filter(slug__isnull=True): item.slug = smart_slugify(item.sector, manager=models.SectorTag.objects, lower_case=True) print "\tsector:", item.slug item.save() for item in models.TechnologyTag.objects.filter(slug__isnull=True): item.slug = smart_slugify(item.technology, manager=models.TechnologyTag.objects, lower_case=True) print "\ttechnology:", item.slug item.save() for item in models.Client.objects.filter(slug__isnull=True): item.slug = smart_slugify(item.name, manager=models.Client.objects, lower_case=True) print "\tclient:", item.slug item.save() for item in models.Page.objects.filter(slug__isnull=True): item.slug = smart_slugify(item.title, manager=models.Page.objects, lower_case=True) print "\tpage:", item.slug item.save() for item in models.CaseStudy.objects.filter(slug__isnull=True): item.slug = smart_slugify(item.title, manager=models.CaseStudy.objects, lower_case=True) print "\tcase_study:", item.slug item.save() for item in models.News.objects.filter(slug__isnull=True): item.slug = smart_slugify(item.title, manager=models.News.objects, lower_case=True) print "\tnews:", item.slug item.save() for item in models.Quote.objects.filter(slug__isnull=True): item.slug = smart_slugify(item.quote[:50], manager=models.Quote.objects, lower_case=True) print "\tquote:", item.slug item.save() if rollback: transaction.rollback() else: transaction.commit()
def order_step_one(request, basket=None): try: basket = Basket.objects.get(id=request.session['BASKET_ID']) except: pass try: order = get_object_or_404(Order, id=request.session['ORDER_ID']) email = order.owner.email house_name_number = order.address.house_name_number address_line_1 = order.address.address_line_1 address_line_2 = order.address.address_line_2 town_city = order.address.town_city postcode = order.address.postcode province_state = order.address.province_state country = order.address.country first_name = order.owner.first_name last_name = order.owner.last_name except: order = None if not basket and not order: problem = _( "You don't have any items in your basket, so you can't process an order!" ) return _render(request, 'shop/order-problem.html', locals()) if request.method == 'POST': post_values = request.POST.copy() initial_values = ( _('First name'), _('Last name'), _('Email address'), _('Your address...'), _(' ...address continued (optional)'), _('Town or city'), _('State'), _('Post / ZIP code'), _('invalid'), ) for k, v in post_values.iteritems(): if v in initial_values: del post_values[k] form = OrderStepOneForm(post_values) if form.is_valid(): # FIRST, GET THE USER if request.user.is_authenticated(): user = request.user else: try: user = User.objects.filter( email=form.cleaned_data['email'])[0] except IndexError: creation_args = { 'username': form.cleaned_data['email'], 'email': form.cleaned_data['email'], 'password': uuid.uuid1().hex, } user = User.objects.create(**creation_args) user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] user.save() try: shopper = get_object_or_404(Shopper, user=user) except MultipleObjectsReturned: shopper = Shopper.objects.filter(user=user)[0] except: creation_args = { 'user': user, 'email': user.email, 'first_name': user.first_name, 'last_name': user.last_name, 'slug': smart_slugify("".join((form.cleaned_data['first_name'], form.cleaned_data['last_name'])), lower_case=True), 'language': get_language(), } shopper = Shopper.objects.create(**creation_args) # CREATE AN ADDRESS OBJECT address = Address.objects.create( owner=shopper, house_name_number=form.cleaned_data['house_name_number'], address_line_1=form.cleaned_data['address_line_1'], address_line_2=form.cleaned_data['address_line_2'], town_city=form.cleaned_data['town_city'], postcode=form.cleaned_data['postcode'], country=form.cleaned_data['country'], ) try: address.province_state = form.cleaned_data['province_state'] address.save() except: pass # if they agree to get an email newsletter if form.cleaned_data['newsletter'] == True: from signals import update_mailing_list update_mailing_list.send( sender=update_mailing_list, email_address=form.cleaned_data['email'], lang_code=get_language(), ) # CREATE OR FIND THE ORDER try: order = get_object_or_404(Order, id=request.session['ORDER_ID']) if not order.hashkey: order.hashkey = uuid.uuid1().hex order.save() except: creation_args = { 'date_confirmed': datetime.now(), 'address': address, 'owner': shopper, 'status': Order.STATUS_CREATED_NOT_PAID, 'invoice_id': "TEMP", 'hashkey': uuid.uuid1().hex, } order = Order.objects.create(**creation_args) order.save() # need to save it first, then give it an ID if settings.AFFILIATE_SESSION_KEY in request.session: order.invoice_id = "TEA-00%sA" % (order.id) order.affiliate_referrer = request.session[ settings.AFFILIATE_SESSION_KEY] else: order.invoice_id = "TEA-00%s" % (order.id) # DO THEY HAVE A VALID DISCOUNT CODE? try: discount = get_object_or_404(Discount, pk=request.session['DISCOUNT_ID']) order.discount = discount except: pass # UPDATE ORDER WITH THE BASKET ITEMS basket_items = BasketItem.objects.filter(basket=basket) for item in basket_items: order.items.add(item) order.save() request.session['ORDER_ID'] = order.id # FINALLY! WE'RE DONE return HttpResponseRedirect(reverse('order_confirm')) # IF THE FORM HAS ERRORS: else: # LOAD EXISTING DATA email = request.POST['email'] house_name_number = request.POST['house_name_number'] address_line_1 = request.POST['address_line_1'] address_line_2 = request.POST['address_line_2'] town_city = request.POST['town_city'] postcode = request.POST['postcode'] country = request.POST['country'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] try: province_state = request.POST['province_state'] except: pass form = OrderStepOneForm(post_values) else: form = OrderStepOneForm() return _render(request, 'shop/forms/order_step_one.html', locals())
def handle(self, *args, **options): if not args or (args and args[0] not in ('rollback','commit')): raise CommandError("USAGE: ./manage.py %s rollback|commit" % \ os.path.basename(__file__).split('.')[0]) rollback = args[0] == 'rollback' transaction.enter_transaction_management() transaction.managed(True) for item in models.SectorTag.objects.filter(slug__isnull=True): item.slug = smart_slugify(item.sector, manager=models.SectorTag.objects, lower_case=True) print "\tsector:", item.slug item.save() for item in models.TechnologyTag.objects.filter(slug__isnull=True): item.slug = smart_slugify(item.technology, manager=models.TechnologyTag.objects, lower_case=True) print "\ttechnology:", item.slug item.save() for item in models.Client.objects.filter(slug__isnull=True): item.slug = smart_slugify(item.name, manager=models.Client.objects, lower_case=True) print "\tclient:", item.slug item.save() for item in models.Page.objects.filter(slug__isnull=True): item.slug = smart_slugify(item.title, manager=models.Page.objects, lower_case=True) print "\tpage:", item.slug item.save() for item in models.CaseStudy.objects.filter(slug__isnull=True): item.slug = smart_slugify(item.title, manager=models.CaseStudy.objects, lower_case=True) print "\tcase_study:", item.slug item.save() for item in models.News.objects.filter(slug__isnull=True): item.slug = smart_slugify(item.title, manager=models.News.objects, lower_case=True) print "\tnews:", item.slug item.save() for item in models.Quote.objects.filter(slug__isnull=True): item.slug = smart_slugify(item.quote[:50], manager=models.Quote.objects, lower_case=True) print "\tquote:", item.slug item.save() if rollback: transaction.rollback() else: transaction.commit()