Essential Django Apps for Every Project

&& [ code, django, python ] && 0 comments

Django projects have the ability to install apps, which are analogous to plugins in other frameworks.

Some of these apps provide simple functionality: django-gravatar installs a template tag for displaying a user’s gravatar in a template. Other apps are large, like Mezzanine which provides an entire CMS framework to your project.

No matter what you are building, you should consider the following apps. I use them in almost all of my projects.

1. Django Extensions

django-extensions is a collection of custom extensions for Django, most in the form of extra management commands. Importantly by installing django-extensions you incur no functional changes so it should be safe to add to almost any project. Here are some of it’s best features:

./manage.py shell_plus: Like the reugular shell management command, but uses ipython instead of the standard python shell. So much more powerful and easy to use. Essential.

./manage.py show_urls: Display the full list of URL routes. Honestly I’m surprised Django doesn’t have a built in command for this, frameworks like Ruby on Rails have had it for years in the form of rails routes.

./manage.py runserver_plus: Launches a development server using Werkzeug instead of the built in one. Werkzeug has some very cool features, like the ability to interactively debug stack traces directly in the browser.

./manage.py generate_secret_key: Does what it says.

These are just a few of the many features django-extensions brings to your project. Check out the full documentation for more.

2. Django Filter

django-filter allows you to declaratively add dynamic QuerySet filtering from URL parameters. If you want your users to be able to order, search or filter results on a page, Django Filter is going to be a huge help. You write Filter classes which define how objects can be filtered then add them to your views where they will automatically modify your queryset for you. They even generate their own forms that you can use if you want.

This might sound a little confusing, so let’s use an example. Suppose you have a Widget model defined in your project:

class Widget(models.Model):
    price = models.IntegerField()
    description = models.CharField(max_length=2000)
    listed = models.DateTimeField()

You have a view where you list these widgets:

class WidgetList(ListView):
    model = Widget

And now you want users on that page to be able to sort by price, search by description, or view all widgets newer than a certain date. You would write a filter that looks like this:

class WidgetFilter(fitlers.FilterSet):
    order = filters.OrderingFilter(fields=['price'])
    description = filters.CharFilter()
    newer_than = filters.DateTimeFilter(field_name='listed', lookup_expr='gt')

Now edit your view to take advantage of your filter:

class WidgetList(FilterView):
    model = Widget
    filterset_class = WidgetFilter

If you want, you can now use the generated form in your template:

<p>Filter results:</p>
{{ filter.form.as_p }}

Regardless, if your view is passed url parameters like this:

http://localhost:8080/widgets/?order=-price&newer_than=2019-03-01&description=foo

The queryset will be filtered accordingly and your user will see the results they expect.

This is just a taste of what you can do with Django Filter. See the full documentation for more features.

3. Django AllAuth

Not every project requires user registration and social authentication capabilities, but many do. django-allauth is an extremely comprehensive package that provides a project with the functions that most users would expect:

  • User sign up flow, including using OAuth providers like Google or Facebook
  • Login/Logout
  • Email confirmation
  • Forgotten password resets
  • “Remember me” session control

This is not stuff most of us want to be hand rolling in our projects. Thankfully Django AllAuth exists and is high quality so we don’t have to.

Notable mentions

django-rest-framework If you’re writing an API, look no further than Rest Framework.

django-storages For projects that need to store static files and media on cloud providers like Amazon S3. Django Storages makes it easy.

Redefining Productivity

&& [ life ] && 0 comments

After nearly 5 years I’ve left my position at Las Cumbres Observatory. During my time there I got to work with scientists on interesting problems in Astronomy. I wrote a lot of code, most of it open source. Without going into too much detail, it was most everything I wanted in a job and probably the best one I’ve ever had.

I can go into details about why I left and my thoughts on full-time vs part-time employment in another post.

For now I’d like to start the new month, and my new “career” by laying out some goals and how I’d like to achieve them. This is for my own benefit: a soft of self evaluation to nobody in particular except myself.

Redefining productivity

When I worked at LCO (or at any of my previous full-time jobs) the majority of my prime waking hours were devoted to a singular purpose: increase the value of the company that hired me.

There were many aspects to full-time work that I found enjoyable: career advancement, relationships with co-workers, and interesting large scale projects that could only be tackled by teams.

I could say that I never stopped being productive in the traditional sense: adding value and making money.

My personal feelings on what it means to be productive in life have changed, however. I feel like I can do more. Now that I’m not employed at a full-time job, I’d like to see if I’m capable and disciplined enough to rise to the challenge.

What I hope to achieve and how

In no particular order:

Still gotta make a living!

I need to maintain a positive income/expense ratio. I hope to achieve this with freelance work as necessary. Eventually, I’d like to launch my own sass that can turn a profit. But more on that later.

Improve my relationships

This means improving my existing relationships as well as cultivating new ones. I’d like to spend more quality time with my wife. Now that I’m more free to travel, I can visit distant family and fiends. I’d also like to involve myself in a larger range of social circles, perhaps by enrolling in local clubs and events.

Intellectual stimulation

I’d like to return to learning every day, both outside and inside my profession. This means tinkering on side projects and trying out new technologies. I’ve taken classes pass/no pass at community college before, which I very much enjoyed and would like to do again. Also, reading and writing.

Maintain my baseline fitness

Exercise is super important to me. I feel better both physically and mentally the more I get. The usual 30min/day rule has never been enough for me. My goal is 9 hours of activity a week. Activities include cycling (obviously), running, surfing and walking. I use Strava to try and track my time. Though that hasn’t worked very well for the surfing…

Create my own source of income

The most difficult goal on this list. I’ve kicked around (and started) many ideas for sass products/businesses over the years. I’ve yet to turn a profit on any of them. Now would be a good time to really focus and see if I can make it happen.

Get better at fixing stuff

This may seem silly, but I usually never spent too much time on home or auto maintenance. I always wanted to use my weekends for other things, so I’d usually pay someone else to do it. I had more money than time, which is a good problem to have. However, there is something innately satisfying about doing it yourself. And it makes you more helpful to others.

What I achieved this week

I’ve only been “on my own” for a week so far. But I feel like I’ve done a pretty good job at working towards my goals:

  • I’ve continued to work on the current freelance projects I already have.
  • I’ve sent in an estimate for another project.
  • I’ve been spending more time in the mornings with my wife instead of trying to squeeze in a longer run or whatever before work.
  • I’ve surfed a lot during the day when nobody else is out! 🏄‍♂️
  • I attended a tech dinner with other freelancers.
  • I started a mailing list sbfreelance for freelancers in the Santa Barbara area. I hope this will help us all network.
  • I signed up for YNAB to help track income/expenses and to budget.
  • I fixed a malfunctioning faucet which had been bugging me for months.
  • I wrote this.

Things I could have done better:

  • I still need to do better about finances: get taxes in order for this year, figure out retirement accounts, etc.
  • I could have spent more time looking for additional work in case my current contracts fall through.
  • I could probably have a little less anxiety, it’s only been a week.

My goals for next month:

  • Keep up with current jobs.
  • Generate at least one more solid job lead in case I need it.
  • Visit a family member.
  • Visit a distant friend.
  • Sign up for a class at the community college, or decide none of them are worth it.
  • Generate at list of 3 sass products and seriously consider if any of them could make a profit.

Badly Designed Bike Racks

&& [ cycling ] && 0 comments

Yesterday I came across what is quite possibly the most badly designed bike rack I have ever seen. May I present to you: the Capitol Bike Rack by Forms+Surfaces.

Capitol Bike
Rack Image credit https://www.forms-surfaces.com/capitol-bike-rack

There were two of these side by side and at first it wasn’t even clear to me that they were supposed to be bike racks (none of them were occupied, of course). Luckily they have a nice bike symbol stamped on them that eased my uncertainty, but not my doubts. Indeed, I found it impossible to lock my bike to one of these using my standard sized U-lock.

I ended up locking my bike to a bench, also designed by Forms + Surfaces, which functioned much better as a bike rack.

These were so bad, that I decided to look them up. I found a spec sheet which claimed that the racks “Meet Association of Pedestrian and Bicycle Professionals (APBP) guidelines.”

Curious, what are these APBP guidelines and how bad do they have to be for this rack to meet them?

It turns out the Association of Pedestrian and Bicycle Professionals do have a pretty good set of guidelines for designing and installing bicycle parking in their Essentials of Bike Parking document.

The following table lists the guidelines and whether the Capitol Bike Rack, the typical “inverted U” rack style, and a sign post meet them:

Guidline Capitol Bike Rack Inverted U Sign Post
The rack should provide two points of contact with the frame. No Yes No
Accommodates a variety of bicycles. No Yes Yes
Allows locking of frame and at least one wheel with a U-lock. Rack tubes with a cross section larger than 2” can complicate the use of smaller U-locks.. No (cross section is 4” according to spec sheet) Yes Yes
Provides security and longevity features. Yes (if you can lock to it) Yes Yes
Rack is intuitive. No Yes Yes

The Capitol Bike Rack fails to completely meet a single guidline provided by the APBP. A no parking sign post meets more. I’m not sure how they can claim that they meet these standards, but it is a blatant lie.

Please, if you are considering installing bicycle parking for your business or development, install racks that actually work. The typical “inverted U” may be boring, but they function.

Cycling in the US: A Dutch perspective.

&& [ cycling ] && 0 comments

Check out this video of a Dutch person’s perspective of cycling in the US:

 

A few of his observations that I found particularly interesting:

  • Cyclists in the US appear to be racing all the time. He attributes this to the need to keep of with other traffic since cyclists are rarely able to ride on dedicated paths and it would be dangerous to move too slowly.

  • People casually riding comfortable bikes, in normal clothing, going from A to B is a sign of a healthy cycling culture. He also uses this as an argument against helmets: they only encourage the image of cycling as a dangerous activity.

He of course makes a few observations that should be obvious to any cyclists in the US.

  • Cycling is seen as an activity for children.

  • Our bike infrastructure really sucks.

It’s great to hear an outside perspective from someone who lives in a place where cycling is so much different than it is here.

Password-store (pass) extremely slow on OSX

&& [ code ] && 0 comments

password-store (installed via homebrew) on OSX is very slow.

Austins-MacBook% time pass testpass
thisisatestpass
pass testpass  0.55s user 0.25s system 83% cpu 0.969 total

Over half a second to print out a password. Pass is just a bash script. This would not do.

After doing some sleuthing, it turns out it is this line in the platform specific code for OSX that is causing the problem:

{{< highlight shell >}} GETOPT=”$(brew –prefix gnu-getopt 2>/dev/null || { which port &>/dev/null && echo /opt/local; } || echo /usr/local)/bin/getopt” {{< / highlight >}}

Every time pass is run on OSX, it first has to run homebrew to find out where gnu-getopt is installed.

It seems silly to default to such a heavy handed approach. It would make sense to first test a well known location (perhaps, the default location where homebrew installs gnu-getopt?) first, and then resort to the other methods after:

{{< highlight shell >}} GETOPT=”$({ [ -x /usr/local/opt/gnu-getopt ] && echo /usr/local/opt/gnu-getopt; } || brew –prefix gnu-getopt 2>/dev/null || { which port &>/dev/null && echo /opt/local; } || echo /usr/local)/bin/getopt” {{< / highlight >}}

Using that method, things are improved considerably:

Austins-MacBook% time pass testpass
thisisatestpass
pass testpass  0.02s user 0.01s system 19% cpu 0.177 total

There have been patches submitted upstream in the past for this issue, but none have been merged. So I forked the upstream repo and applied the fix. You can install this version of pass using homebrew:

Uninstall pass if you already have it installed via brew:

brew uninstall pass

Then “tap” the repo:

brew tap Fingel/pass-osx

Finally, install the formula:

brew install fingel/pass-osx/pass

Enjoy a properly fast pass. This should be helpful for anyone using pass on OSX, who doesn’t mind installing their password manager via some random guy’s fork on Github… 🤔

Does Strava Encourage Illegal Trail Riding?

&& [ cycling ] && 1 comments

I recently received the following email in my Trail Care inbox (names and locations removed):

Hi, I am a long time mtb rider. I am also on the Board of Directors for the local open space advocacy/trails stewardship group. The actual owner of the surrounding open space is the county. Like other areas, we have a ton illegal trails. Many of the authorities see Strava as a negative in that riders publicly post their illegal trail rides which leads others to follow. There is also the perception that Strava motivates riders to break speed limits to get KOMs. Have you run into this anywhere else and how do you get around this?

This is a controversial subject within the mountain biking community, especially within the advocacy circles. Pretty much everyone has an opinion about Strava. Some people love it, some hate it, any everyone has their theories.

What nobody has is any data to back up their arguments. None.

Nobody can prove that Strava encourages illegal trail riding. You’d have to hang at the bottom of an illegal trail for months and ask every rider where they found out about it, compare it to months of data prior to Strava coming into existence, and even then you’d only (maybe) be able to come to a conclusion for that one trail.

You can’t prove that Strava doesn’t encourage illegal trail riding either - but not being able to prove a negative does not prove a positive.

When people say that Strava encourages illegal riding what they might really be saying is that the narrative makes sense to them. It is also very easy to blame a scapegoat, Especially when it’s a phone app coming out of Silicon Valley. I get it: I have sympathy for people that feel like phone apps have no business out on the trails. But to each their own, right?

Unfortunately telling people that they can’t prove Strava is a problem doesn’t really win any arguments. - people much prefer anecdotal and circumstantial evidence. So I’ll give you some of my personal theories:

I (as I hope I made clear) have no idea if Strava contributes to illegal trail riding. What it surely does is make it more visible to non mountain bikers. Illegal mountain bike trails have existed since people first started riding bikes off road, but maybe not too many people knew that it was happening. Trust me, it has been. You would especially think that land managers/owners might prefer to think that Strava is contributing to more people riding illegal trails when in reality they have been all along, right under their noses!

As for speed, I have to think that’s most likely bullocks. Mountain bikers love to go fast, otherwise they’d be hikers. Mountain bikes have gotten a lot faster in the last decade, at the same time the sport has become much more accessible and popular. This will of course result in occasional conflicts on multi use trails.

So in short: while I have no idea, I highly doubt Strava contributes significantly to increased use of illegal trails. Southern California especially, with it’s very few and overcrowded trails, faces huge challenges in land and recreational management. Blaming a scapegoat doesn’t actually solve any problems. Land managers and other trail users need to work with mountain bikers to come up with real solutions, not blame some silly app.

Dec 4th Goleta City Council on Scooter Share

&& [ other ] && 0 comments

I attended and spoke at the December 4th Goleta city council meeting at which they brought forward an urgency ordinance to ban the operation of on demand scooter sharing services (Lime, Bird) in the city of Goleta.

There were 34 speaker slips submitted and the meeting did not end until 10:30pm. Public comments appeared to be split 50/50 in favor/opposition to the ban. I do take some issue with the business practices of Bird and Lime but I believe the benefits of scooter sharing programs outweigh the cost.

There were many other speakers more eloquent and prepared than I that spoke to the social, economic and environmental benefits to transportation alternatives, so I kept my time short. Here’s what I said as best as I can recall:


Good evening council members, thanks for having me.

I live in Isla Vista and work just around the corner here. I do occasionally, when I’m too lazy to ride my bike, take a Bird to work. If you’re looking for someone to blame for the Bird invasion of Goleta, I’m definitely a case.

I’d like to speak to some of the perceived hazards of the scooters. First, is the supposed danger of them. They can’t be any more dangerous than bicycles, and as some of the first responders here can attest, certainly no more dangerous than cars, which kill 20,000 Americans a year.

The other is this idea that they are somehow visually offensive. I live on a street with street parking and when I leave my house in the morning I certainly don’t appreciate having to see someone’s 6 inch lifted Ford F-650 parked out front nor do I like to see a Prius covered in kombucha and yoga stickers. See all of this is relative and I think what we’re seeing is a knee jerk reaction.

I do think these companies need to be regulated, but I don’t think they should be banned outright. So I ask you please do not do anything rash.

Thank you.


In the end, to nobody’s surprise, the ordinance to ban scooter share companies passed.

Reliable California Wildfire Information

&& [ other ] && 0 comments

November is wildfire season in California, and this year has been no exception. Just when we thought it couldn’t get worse than 2017 / 2018, it did.

Unfortunately it can be super hard to get good information about wildfires while they are happening. This is mainly due to every local news station eagerly exploiting tragedy for readership. Googling a fire returns pages of poorly and hastily written articles that contain, at best, out of date information (but plenty of shocking cell phone video) and at worst no information at all.

If you are in danger of wildfire, you should always follow the direction of your local emergency agencies.

If you’re one of the other 40 million Californians that just want get some straight information about fire boundaries, conditions and smoke without all the hysteria and FUD, here are some official and reliable sources:

InciWeb

iciweb

InciWeb is an incident information system provided by the National Wildfire Coordinating Group (NWCG). Basically, it aggregates the latest information about wildfires directly from the local agencies that are in the affected area.

The site provides basic information, the current situation, outlook and latest reports from the commander(s) on the fire. This is the most reliable place to get information such as cause, location, size, containment, as well total personnel and estimated containment dates.

I guarantee InciWeb is where 99% of all local news companies get their information. Skip the middleman.

National Fire Situational Awareness Map

nfsa

The National Fire Situational Awareness Map is an interactive map that overlays data directly from infrared satellites that can detect fire from orbit. This data is used to make a map that very accurately shows where fires are burning at any one moment. It also displays historical burn areas. Absolutely the best way to see where and how hot a fire is burning. This service is also provided by the NWCG.

NASA EOSDIS Worldview

earthview

Wile not specific to wildfires, Nasa’s Worldview application is another interactive map that shows near realtime satellite images of the earth as quickly as 3 hours after observation. This is very similar to the National Fire Situational Awareness Map except that it displays it’s data in the optical instead of infrared, and it allows you to go back in time. This is super useful for viewing current air quality conditions and tracking smoke as it moves across the state (and country). An amazing resource provided by the good folks at NASA.

Those are my go-to’s. Do you have other resources you use during wildfire season? If so, let me know in the comments!

Simple Virtualenv Auto Activation With ZSH.

&& [ linux ] && 1 comments

Since I moved from fish to zsh, one of the main things I missed was virtualfish. I’m not sure how any serious python developer lives without auto activation, as in automatically activating the virtualenv for your project when you open a terminal or cd to it.

Here is a script you can use to achieve auto activation. It doesn’t require virtualenvwrapper, pyenv, or anything like that. Just use python3’s built in python -m venv to create a virtualenv in ~/.virtualenvs/, use the provived venvconnect function to connect the activated env with the current directory, and you’re done.

#!/bin/zsh
#
# Auto activate a python virtualenv when entering the project directory.
# Installation:
#   source virtualenv-auto-activate.sh
#
# Usage:
#   Function `venvconnect`:
#       Connect the currently activated virtualenv to the current directory.
#
VENV_HOME=$HOME/.virtualenvs

function _virtualenv_auto_activate() {
    if [[ -f ".venv" ]]; then
        _VENV_PATH=$VENV_HOME/$(cat .venv)

        # Check to see if already activated to avoid redundant activating
        if [[ "$VIRTUAL_ENV" != $_VENV_PATH ]]; then
            source $_VENV_PATH/bin/activate
        fi
    fi
}

function venvconnect (){
    if [[ -n $VIRTUAL_ENV ]]; then
        echo $(basename $VIRTUAL_ENV) > .venv
    else
        echo "Activate a virtualenv first"
    fi
}

chpwd_functions+=(_virtualenv_auto_activate)
precmd_functions=(_virtualenv_auto_activate $precmd_functions)

Source the above script in your ~/.zshrc and you should get auto activation of python virtualenvs.

A Piece of Trash a Day

&& [ earth, other ] && 0 comments

The lines we make in our day to day lives. Placed on a heatmap of all our motion, our daily routines show up in blazing hot purple. We ride down the same streets on our way to work, walk the same sidewalks to get the groceries, wander familiar shorelines on sunset strolls.

One thing I notice on a daily basis is trash. At it’s best litter is a faint reminder of civilization’s negative impact on the landscape. At it’s worst it’s an immediate and unwelcome distraction from the moment’s thoughts or reveries.

I wonder: considering how often I travel the same paths, can one person simply picking up a piece of trash a day make a noticeable difference in the amount present? I suspect so, as the places I walk aren’t particularly polluted and I do travel them quite often.

So I begun today by picking up a broken pair of safety glasses and a 5 hour energy drink, both on the side of the sidewalk I pass during my lunch walk, and that I had been noticing for at least the last month. The walk has been improved already.

Tomorrow: Dorritos bag.