Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Making simple map images with qGIS
Occasionally you just need a quick map, and it’s not going to be used for interaction or even necessarily display on the internet (say a Keynote/PowerPoint presentation, for example). We could build it as a Google map, get a gigantic computer monitor and fullscreen the window and take a screenshot, and have it look like every other web map out there – or we can reach into the toolbox of those who are NOT neogeographers and borrow a few things. For me this tool is still qGIS (for Mac check out KyngChaos for binary builds), though there are alternatives like GRASS GIS and TileMill, to name only a couple. (TileMill is actually designed to create tiles similar to how Google Maps / OpenStreetMap do it, but you can shoehorn it to do “print” maps) Of course, it bears repeating that the results from doing this are not survey quality. Don’t use my recommendations / guidance to determine where not to dig to avoid buried lines, where to build a road, or anything else. But zoomed back a ways where the dot on the map is easily the size of a 40,000 population town, it’s close enough. Since this is a … -
Working with files in Django – Part 2
First part of this article is here. How to setup file serving for development server As I mentioned earlier, it is best to serve files on a fast HTTP server. But this setup is overkill for development environments, you can safely let Django handle your files. The snippet below relies on the assumption, behind the [...] -
Putting it all together, part 3
Now we make our code restrict to things near the user when they allow geolocation…but the results aren’t really what we’re shooting for. def earthquake_display(request): search_origin = False if request.GET.get('lat') and request.GET.get('lon'): search_origin = Point(float(request.GET.get('lon')), float(request.GET.get('lat'))) weekago = datetime.datetime.now() - datetime.timedelta(days=7) quakes = Quake.objects.filter(datetime__gte=weekago).order_by('-datetime') last_check = cache.get('usgs-poll-last-finished', datetime.datetime(2000, 1, 1)) checking = cache.get('usgs-poll-in-progress', False) if not checking: cache.set('usgs-poll-in-progress', True) latest_quake_ago = datetime.datetime.now() - quakes[0].datetime latest_check_ago = datetime.datetime.now() - last_check if latest_quake_ago > datetime.timedelta(minutes=90) and latest_check_ago > datetime.timedelta(minutes=90): from django.core import management management.call_command('load_quakes') cache.set('usgs-poll-last-finished', datetime.datetime.now()) # and refresh the QuerySet to get the new data quakes = Quake.objects.filter(datetime__gte=weekago).order_by('-datetime') cache.delete('usgs-poll-in-progress') checking = False if search_origin: quakes = quakes.distance(search_origin).order_by('distance', '-datetime') quakes = quakes[:25] return render_to_response('earthquakes.html', { 'object_list': quakes, 'checking': checking, }, context_instance=RequestContext(request)) <html> <head> <script src='http://media.adamfast.com/QueryData.compressed.js'></script> <script language='JavaScript'> function checkLocation() { var getData = new QueryData(); if ('lat' in getData) { } else { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( function (ppos) { window.location.href = window.location.href + '?lat=' + ppos.coords.latitude + '&lon=' + ppos.coords.longitude; }, function (err) { switch(err.code) { case err.TIMEOUT: alert('Attempts to retrieve location timed out.') break; case err.POSITION_UNAVAILABLE: alert("Your browser doesn't know where you are.") break; case err.PERMISSION_DENIED: alert('You have to give us permission!') break; case err.UNKNOWN_ERROR: alert('Unknown error returned.') break; default: … -
Goodbye
Hi everyone, unfortunately, Thomas and I have to say goodbye to our open-source community. We started contributing because we thought it was interesting and we had fun building something together. However, our projects have stopped being fun. We're not even using most of them, anymore (not even at our startup). This is why we've made a final decision: We've stopped maintaining our open-source projects. All of them. This primarily affects djangoappengine users. The MongoDB backend has its own capable contributors, so django-mongodb-engine users should be unaffected by this. We're really sorry, especially to those who have a business that depends on djangoappengine. Thanks to everyone who has supported us. If anyone is interested in continuing djangoappengine development, please send a mail to the Django-nonrel discussion group. Best wishes, Waldemar and Thomas Update: Thanks for your warm response! We really didn't expect that. Wilfred Hughes offered to take over, so hopefully our projects won't die. By the way, I'll try to keep blogging about web development, NoSQL, and App Engine. There's a whole lot of stuff we've learned and keep learning at our startup and I'd like to share that with you from time to time. Please also read the comments … -
30 second apache/nginx/gunicorn timeout
-
A day of thanks
In the spirit of the holiday (in the US we’re celebrating Thanksgiving) I thought I’d offer my appreciation / thanks to the projects I use and lean on to make my applications work. This isn’t a canonical list, I’m sure I’ve forgotten libraries here and there. And regardless of whether I use your code right now or not, thanks for releasing it where I can someday if it does something I need. I contribute everything I can when I can because everybody else has contributed so much that makes me more productive I want to follow suit. If you blog, I’d ask you to consider something alone these lines of your own. As software authors there are lots of instances where our code is doing things we have no idea about until we’re told. Python language Django django-socialregistration (I’ve got my own fork of this but it existing saved me a bunch of time!) dateutil PostgreSQL PostGIS Coverage.py django-coverage GeoPy python-twitter Metar Arduino – platform, software and hardware. I love these things and enjoy prototyping with them. This is in addition to all the OTHER stuff I use besides libraries – GitX, VLC, Audacity, QGIS, TileMill and others I’m sure. … -
Putting it all together, part 2
We’ve got our quakes app installed (update it if you’re following along at home, I committed a bunch of code changes for this entry) and our initial data imported. However, we need this data to be updated somewhat regularly for the service to be useful. Sean shipped django-quakes with Celery support (which I commented out of the requirements file because I’m running this app on the neat ep.io auto-scaling webapp service‘s free tier and don’t have Celery access. If you run Celery just re-enable it, if you don’t use Celery or even know what it is (check it out!) you can use cron to schedule it just as well. To avoid polling too often and bugging the USGS I’d set the interval at hourly or more under normal circumstances. We only care about quakes when our users do. I’d run it at least daily though so you keep history. Since we care when our users do and earthquakes can’t be convinced to ONLY hit at certain minutes after the hour, what do we do? How about we check the latest quake we have and see if it’s beyond a certain age to force a refresh? This is more of that … -
Preventing brute-force attacks with django
Brute-force attack prevention is a topic that gets mentioned every now and then in the Django community, on mailing-lists and at conferences. I've been thinking about this a little bit and I believe I found a very nice solution. Note that I'm only tackling the issue of brute-forcing user credentials, not rate-limiting in general. There are a bunch of ways to monitor login attempts: With a decorator applied to every login view, With a middleware that inspects incoming requests (note: this is a bad idea), With Nginx (or whatever your web server is), using HttpLimitReqModule Neither of these solutions are optimal: the admin accepts login attempts at arbitrary URLs, which makes it difficult to monitor, there are different ways to authenticate users, maybe you have an API that does Basic authentication, the nginx syntax is hard to get and maybe some day you'll need to move to something else. The solution is to put the rate-limit logic and the credentials verification logic at the same place: on the authentication backend. To do this, we need to make the authentication backend request-aware, in order to block people based on some criteria such as their IP or User-Agent. This requires: A custom … -
AJAX Pagination with handlebars.js
AJAX Pagination with handlebars.js -
To Django Con and beyond
My journey to Django Con Amsterdam and beyond -
How to install virtualenv on webfaction
How to install virtualenv on webfaction -
How to install virtualenv
Find out why and how to install virtualenv -
Added Haystack search with Whoosh to this site
Added Haystack search with Whoosh to this site -
Display Django and Python version numbers on your site
Display Django and Python version numbers in template -
Putting it all together: A sample, simple project, part 1
We’ve discussed all sorts of things this month, now it’s time to start putting them together more completely than snippet-for-this, snippet-for-that. I’m not going to inline command + output on everything but I am going to spell out all of the steps – if you have trouble, let me know in the comments. To accomplish this we’re going to build a simple web service I’ve snagged “isthatanearthquake.com” for. First order of business is creating the project. Because virtualenv and virtualenvwrapper rocks (`pip install virtualenv virtualenvwrapper`), I started with `mkvirtualenv isthatanearthquake`. My global virtualenv `postactivate` script includes the line `cd $VIRTUAL_ENV` which drops me in the env whenever I activate it. Next I created a `src` directory, created and cd’ed into `isthatanearthquake-git`, created `templates` and created requirements.txt with these contents: django==1.3.1 psycopg2==2.4.2 -e git+git://github.com/adamfast/django-quakes.git@4d9fcdb4978a28f35d1e32406a81f3b8b5d58845#egg=quakes pip install -r requirements.txt gets me Django, Postgres and the reusable app django-quakes (thanks Sean Bleier, who I’ve forked the library from for this example) installed in my virtualenv. Create the Django project with `python $VIRTUAL_ENV/lib/python2.?/site-packages/django/bin/django-admin.py startproject isthatanearthquake` (note you will need to specify your python version in this command) `add2virtualenv isthatanearthquake` will make the new project show up on your PYTHONPATH. Open isthatanearthquake/settings.py and `import os` … -
Adding CoffeeScript
With CoffeeScript becoming more and more popular it is time to start using it. This video is about how to get CoffeeScript added to your project so you can start developing with it.Watch Now... -
Adding CoffeeScript
With CoffeeScript becoming more and more popular it is time to start using it. This video is about how to get CoffeeScript added to your project so you can start developing with it.Watch Now... -
Custom Admin Filter Specification
Let's say we have a model Project with age groups as boolean fields: class Project(models.Model): # ... age_group_0_5 = models.BooleanField(u"From 0 to 5 years") age_group_6_12 = models.BooleanField(u"From 6 to 12 years") age_group_13_18 = models.BooleanField(u"From 13 to 18 years") age_group_19_27 = models.BooleanField(u"Fron 19 to 27 years") # ... In order to list them as one selection in the admin list filter, we need a specific filter specification. Let's create it in the admin.py: from django.contrib.admin.filterspecs import FilterSpecclass AgeChoicesFilterSpec(FilterSpec): def title(self): return u"Age group" def __init__(self, f, request, params, model, model_admin, field_path=None): super(AgeChoicesFilterSpec, self).__init__(f, request, params, model, model_admin, field_path=field_path) self.request = request def choices(self, cl): yield {'selected': not( self.request.GET.get('age_group_0_5', None) or self.request.GET.get('age_group_6_12', None) or self.request.GET.get('age_group_13_18', None) or self.request.GET.get('age_group_19_27', None) ), 'query_string': cl.get_query_string( {}, ['age_group_0_5', 'age_group_6_12', 'age_group_13_18', 'age_group_19_27']), 'display': u'All'} yield {'selected': self.request.GET.get('age_group_0_5', None) == 'True', 'query_string': cl.get_query_string( {'age_group_0_5': 'True'}, ['age_group_6_12', 'age_group_13_18', 'age_group_19_27']), 'display': u"From 0 to 5 years"} yield {'selected': self.request.GET.get('age_group_6_12', None) == 'True', 'query_string': cl.get_query_string( {'age_group_6_12': 'True'}, ['age_group_0_5', 'age_group_13_18', 'age_group_19_27']), 'display': u"From 6 to 12 years"} yield {'selected': self.request.GET.get('age_group_13_18', None) == 'True', 'query_string': cl.get_query_string( {'age_group_13_18': 'True'}, ['age_group_0_5', 'age_group_6_12', 'age_group_19_27']), 'display': u"From 13 to 18 years"} yield {'selected': self.request.GET.get('age_group_19_27', None) == 'True', 'query_string': cl.get_query_string( {'age_group_19_27': 'True'}, ['age_group_0_5', 'age_group_6_12', 'age_group_13_18']), 'display': u"From 19 … -
GDD - RSS Feeds
I've decided to start a new occassional series, called God Dammit, Django. If I say "God DAMMIT, Django!" more than three times in one coding session before solving my problem, that's a sign that I need to blog about the solution. Why do this? One of my regrets as I've ... -
Django permissions are untranslatable
-
Working with files in Django – Part 1
In this post what I mean by file is any content that is not dynamically generated. There are basically two types of files a web application deals with: Files that are hard coded in templates or in code. We will call them STATIC files. Files that are referenced in the code but only known in [...] -
Python os.stat times are OS specific …
A pitfall I faced while I was playing with PyTDDMon. It appeared that os.stat times return different type of values int and float depending on the OS. Fortunately this can be avoided with the help of stat_float_times. -
Finding Data: Often harder than using it
One of the hardest parts of doing geo projects is getting the data you need to do it in the first place. In the US at least there are mountains of data at the federal level, some at the state level and who knows what at the local level. There isn’t a single place I can go to for anything outside of census-type stuff. Which school for a given grade level would a child at this point attend? Maybe it’s published, maybe it’s not. Most cities or counties will have a GIS department. Some of them will be great, and helpful towards your goal as a developer. Others won’t. Our world of the tools and technologies are leapfrogging traditional methods. So here’s some of my favorite sources of different kinds of data, worth looking at for your next project. TIGER/LINE: Gigabytes of shapefiles of things the US Federal government collects. I tend to look here first if I need basic location data. SimpleGeo Places DB: SimpleGeo put a dataset of 21 million places (12ish million in the US) into the public domain last summer, and links to the file here. I have played with the data some and it’s pretty … -
Django Suite II: Configurando nuestro proyecto de manera correcta.
En esta entrada abordaremos un tema importante: la configuracióndel proyecto. Como dije en la entrada anterior, en configuraciones tampoco hay una manera definitiva de hacer las cosas ya que la flexibilidad de Django nos lo permite. Django usa archivos Python para guardar configuraciones, aprovecha la manera de trabajar del lenguaje para hacer archivos de configuración fáciles de leer, extender y utilizar dentro de nuestros proyectos. Normalmente al iniciar una aplicación creamos un proyecto en blanco con el comando startproject que nos crea una carpeta con los archivos necesarios para iniciar. Por defecto estas configuracionestienen ciertos valores de los cuales normalmente nos molestaremos en cambiar sólo algunas, como configuración de bases de datos, ubicación de archivos estáticos y servidor de correo. Acá algunos trucos para hacer estas configuraciones de manera dinámica y distribuibles para usarse en sistemas de control de versiones: Separación del archivo settings.py Este archivo contiene muchas veces datos sensibles que no pueden ser publicados o simplemente varían de una estación de trabajo a otra, por lo que conviene separarlo con un archivo extra que por convención lo llamamos"settings_local.py" acá deberán ir estas configuraciones: DATABASES ADMINS DEBUG TEMPLATE_DEBUG SECRET_KEY (si lo vas a hacer código libre y público) Claves … -
Django Suite II: Configurando nuestro proyecto de manera correcta.
En esta entrada abordaremos un tema importante la configuración del proyecto, a como dije en la entrada anterior en configuraciones tampoco hay una manera definitiva de hacer las cosas, ya que la flexibilidad de Django nos lo permite. Django usa … Continue reading →