Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django Update View without slug in the url
Today I wanted to use the Django Class Based View (CBV) UpdateView but without a slug identifier in the URL. For example, instead of /profiles/pydanny/ I would go to /my-crazy-profile/. Also, I needed to force authentication. I've done this with Django functional views a few times times, but today I did it in Django. This is what I did: 1. Added django-braces to my project Kenneth Love and Chris Jones' awesome django-braces package has some very handy mixins for working with Django CBVs. Kenneth and Chris really understand CBVs, specifically on how to extend them, and have provided a bunch of really useful utility methods in the django-braces library. Yeah, I could figure this stuff out on my own, but since those guys already did the hard work I might as well just lean on them. pip install django-braces==0.1.3 # settings.py INSTALLED_APPS = ( ... 'braces', ... ) 2. Wrote the view Assuming a very simple profile Model and Form (which they weren't - but that's not what this post is about), this is how I implemented the view: # profiles/views.py from django.views.generic import UpdateView from braces.views import LoginRequiredMixin # handles authentication from profiles.forms import ProfileForm from profiles.models import Profile … -
Redirect to Custom URL After Saving in Django Admin
Here's a quick and dirty admin hack that can save you *lots* of time if you're used to browsing between editing objects in admin and vieving the results on a live site. Put following `change_view`-method in your `admin.py` and now you can make links to admin change page that return you back to where you came from: ```python class BlogEntryAdmin(admin.ModelAdmin): ... def change_view(self, request, object_id, form_url='', extra_context=None): result = super(BlogEntryAdmin, self).change_view(request, object_id, form_url, extra_context) if request.GET.get('return_to', False): result['Location'] = request.GET['return_to'] return result ``` In your template you'd have something like: ```django {% if request.user.is_staff %} <a href="/admin/blog/blogentry/{{ entry.pk }}/?return_to={{ entry.get_absolute_url }}">Edit in admin</a> {% endif %} ``` Of course, if you're smart, you should convert any places that need this kind of functionality with frontend editing tools so you can forget going to the Admin in the first place. But meanwhile, those few lines of code may come in handy! -
Redirect to Custom URL After Saving in Django Admin
Here’s a quick and dirty admin hack that can save you lots of time if you’re used to browsing between editing objects in admin and vieving the results on a live site. Put following change_view-method in your admin.py and now you can make links to admin change page that return you back to where you came from: class BlogEntryAdmin(admin.ModelAdmin): ... def change_view(self, request, object_id, form_url='', extra_context=None): result = super(BlogEntryAdmin, self).change_view(request, object_id, form_url, extra_context) if request.GET.get('return_to', False): result['Location'] = request.GET['return_to'] return result In your template you’d have something like: {% if request.user.is_staff %} <a href="/admin/blog/blogentry/{{ entry.pk }}/?return_to={{ entry.get_absolute_url }}">Edit in admin</a> {% endif %} Of course, if you’re smart, you should convert any places that need this kind of functionality with frontend editing tools so you can forget going to the Admin in the first place. But meanwhile, those few lines of code may come in handy! -
Sunlight and Open Source
David Eaves has a thoughtful post over at TechPresident talking about open source and the transparency community's commitment to it -- a commitment that David sees as half-hearted. Sunlight's mentioned in the post, and the MySociety initiative that prompted the post is something that our team has been thinking about a lot. I think there's something to David's criticisms. But he's missing a few important things. But let's get the baseline stuff out of the way first. Sunlight loves open source. Our whole stack is built on it, from the Varnish cache your browser connects to, to the Django/Rails/Flask/Sinatra/whatever app behind it, to the Postgres/Mongo/Redis/Solr/elasticsearch datastores that powers it, to the OpenOffice suite that edits the grant application that paid for it all. All of our stuff is up on GitHub, and we welcome and celebrate contributions from the community. But, Kindle contest aside, the above examples are mostly about us benefiting from open source. What have we done for the movement lately? This is the crux of David's critique: So far, it appears that the spirit of re-use among the big players, like MySociety and the Sunlight Foundation, only goes so deep. Indeed often it seems they are limited … -
django-statsd 0.3.6.1
I just released django-statsd 0.3.6.1. I've been doing lots of incremental pushes of django-statsd over the last few months. In the last versions I added the following... A log client that will just log to a python logging handler. This is quicker and easier to set up than the toolbar which is still fraught with pitfalls. A quick example would be setting this: STATSD_CLIENT = 'django_statsd.clients.log' LOGGING = { 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'statsd': { 'handlers': ['console'], }, }, } ... and you'll get the statsd pings in your console. Useful for development. I've been collecting navigation timing on Mozilla sites for a while, but they haven't been supeer useful. In an attempt to copy what New Relic do, I started parsing the timing data in a similar manner. Giving some new statistics from navigation timing: network, app, dom and rendering. Although I think I still need to refine those. Finally, if you can get Django debug toolbar and django-statsd working together, you should now be rewarded with a nice waterfall view of the timings, for example: That's it for now. -
Two talks accepted by DjangoCon
I'm happy to report that the DjangoCon schedule has been announced and we have two presentations that made the cut. Joe Jasinski will be making the solo presentation, "So You Want to Make a Payment: Comparing and contrasting Django payment options" which will introduce and compare some common payment ... -
__name__ for Python class and Python function
This is my first post in the series of small random learnings. The attribute __name__ is by default present in every python function. But suprisingly an object of a class doesnt have this attribute unless specifically specified. class example(): def classFunction(): return "test" obj = example() print obj.__name__ #This is an error On the other hand , def functionA(): return "A" def functionB(params): return params.__name__ print functionB(functionA) # prints functionA -
Installation de virtualenvwrapper chez Alwaysdata
J’ai il y a quelques temps fait de multiples tests chez AD. Certains nécessitaient l’utilisation de paquet python non installé par défaut sur le serveur mutu AD. Du coup, j’ai voulu installer virtualenwrapper pour me simplifier la tache. Voici la méthode que j’ai utilisé. Je suis preneur de toute amélioration que vous pourriez me remonter sur ma manière de faire (pour le jour où j’aurais vraiment besoin d’installer des choses pour faire de la prod avec du virtualenv). D’ailleurs je la partage ici autant pour le plaisir de la partager, que pour ne pas l’oublier que pour vous permettre de l’améliorer. Le commencement, installer virtualenwrapper. En local sur son home. En faisant : pip install --install-option="--user" virtualenvwrapper du coup cela vous installe le tout dans $HOME/.local/…. Une fois installé, il faut faire (comme pour installation normale) la création du répertoire de vos environnements en faisant : export WORKON_HOME=$HOME/.virtualenvs mkdir -p $WORKON_HOME Ensuite histoire de ne plus avoir à le faire, dans votre .bash_profile : export PYTHONPATH=~/.local export WORKON_HOME=~/.virtualenvs export PATH=$PATH:$PYTHONPATH/bin source ~/.local/bin/virtualenvwrapper.sh un petit coup de source ~/.local/bin/virtualenvwrapper.sh et Voila ! (à dire comme avec l’accent d’un américain qui prend un accent français). Vous aller pouvoir faire des mkvirtualenv en … -
Django Workshop at Free Software Master 2012
Last weekend I gave my annual Django workshop for this year’s students of the Free Software Master that Igalia organizes. When I started with Django it was 2007 and I was happy with its version 0.96 Currently with its version 1.4, the path that it took and the improvements it has got are incredible and it is used by many interesting companies and organizations. My presentation for this year’s workshop covers more things and is based on Django 1.4. You can check it out below, the license is Creative Commons as usual: (direct link to presentation in SpeakerDeck) -
UnicodeEncodeError when uploading files in Django using Supervisor and Gunicorn
Issues related uploading files with unicode filenames have long history with Django and Linux. There are many stack overflow questions and blog posts on the subject already, but very few deal with solving the problem when using Supervisord and Gunicorn directly. If you are using apache2 and mod_python you can configure your as per the docs: https://code.djangoproject.com/wiki/django_apache_and_mod_wsgi#AdditionalTweaking Fundamentally all fixes have the same goal: configure the environment of the server running Django to use the correct locale, so sys.getfilesystemencoding() will return 'UTF-8' instead of 'ANSI_X3.4-1968'. What makes solving this problem especially hard is there are many possible solutions and picking the right one for you situation can be difficult. Ignore Nginx Related Advice Since you are using Gunicorn, I am going to guess you are using Nginx and you will come across posts saying you need to add charset utf-8 to the http section in the root Nginx config file. Though doing this is probably generally a good idea, it will not solve the problem. Nginx knows nothing about Python, Django or Gunicorn, except that when it makes requests down a unix or TCP socket it gets back bytes. No setting in Nginx will affect the environment Python is running … -
Spurious CORS Errors from Sentry
I realised the other day that [Sentry][sentry], the awesome system we have been using for a while to track our error logs from our [Django][django] project, can also be used to track exceptions from other systems. Like Javascript. In fact, there is a client available: [raven.js][ravenjs]. So, we have a server set up for work, but I have a side-project I have been working on, Workout Builder. So, I thought I'd set up a server in [Heroku][heroku] to act as my sentry server. And I found a nice simple way to get up and running: Daniel Watkins has a nice post over at [Odd_Blog][odd-blog], [Deploying Sentry on Heroku][odd-blog-sentry]. It's pretty straightforward, and extremely simple. I got it up and running in no time, and then attempted to set up an email service. Rather than use my actual account for sending, I thought I'd set up a sending-only account at my domain, hosted as a Gmail Apps domain. So, I set it up, and set about testing. All of a sudden, I'm getting errors, that didn't appear for 30 seconds, that my test domain is not permitted to send a request due to CORS. But, I had been sending them previously. … -
Django Training
Caktus is proud to announce that we are now offering Django training services. This new service includes both off and on-site training for you and your team to become a Djangonaut. We kicked off this new service by hosting a Django Bootcamp at the Caktus office. It was a wonderful experience and our trainees came ... -
apibaleares.com
El dimecres passat vàrem posar en producció la nova web de portal immobiliari del Col·legi Oficial d'Agents de la propietat immobiliària de les Illes Baleares, que es mostra baix el domini http://www.apibaleares.com. Com és habitual és una aplicació feta amb Django, i amb la idea de que sigui una aplicació escalable i sobretot mantenible. El sector immobiliari no passa pel seu millor moment, tot val a dir-ho, però és un projecte que m'ha fet especial il·lusió. Per una part significa tractar amb molta gent que fa servir el programa, cada un amb les seves pròpies sensibilitats, i en un sector on la tecnologia informàtica s'obre pas molt a poc a poc. És un dels primers projectes que fem amb Django 1.4, així que aprofitaré per fer cinc cèntims del que ha representat. Django 1.4 canvia un poc l'estructura dels projectes per a fer-los més modulars. Per la nostra banda hem aprofitat per també seguir amb el camí iniciat amb PropietariosOnline i SpokenPic i desenvolupar tota l'estructura de vistes mitjançant les class bassed views. Tot i que hi ha gent a favor i en contra, he de dir que ara per ara, i pels tipus de projectes que fem les CBV … -
PyFlakes-clean import of local_settings.py
Any project have own bunch of settings for different environments: for dev, production, staging. Everyone use it on daily basis. But annoying thing is that PyFlakes, great code analysis tool, warn about that. And it's reasonable.So, to have this functionality, but without warning I use this pattern:try: import local_settings for setting in dir(local_settings): if setting.startswith('_'): continue locals()[setting] = getattr(local_settings, setting)except ImportError: passSimple and useful!Update: I've added ignore of attributes which starting with underscore. Thanks to Igor Davydenko -
Running a Django (or any other) dev instance over HTTPS
Being able to run your dev instance over HTTPS is really useful: you might spot some weird bug that would have bitten you in production, and if you do find one, you can debug it much more easily. Googling for this subject resulted in several different tutorials using stunnel, but all of them broke in some way on my machine running Ubuntu Maverick. So here is how I got stunnel working – perhaps it will help someone else too: sudo aptitude install stunnel sudo su - cd /etc mkdir stunnel cd stunnel openssl req -new -x509 -days 365 -nodes -out stunnel.pem -keyout stunnel.pem openssl gendh 2048 >> stunnel.pem chmod 600 stunnel.pem logout cd Now create a file called dev_https with the following text: pid= foreground=yes debug = 7 [https] accept=8443 connect=8000 TIMEOUTclose=1 Note: this assumes your web server is running on port 8000. If it’s not, change the value of “connect” to the appropriate port. Finally, run: sudo stunnel4 dev_https Now if you go to https://localhost:8443/, you should see your HTTPS-enabled dev instance! Note: To properly simulate a HTTPS connection in Django, you should also set an environment variable HTTPS=on. Without this, request.is_secure() will return False. You could set it … -
July 15th, 2012 LA Open Source Recap
On July 15th, 2012, at the July LA Hackathons Open Source event, over 60 Python, Django, Ruby, Ruby on Rails, PHP, JavaScript, Node.js, Perl, and Clojure developers arrived to work on a variety of projects. We went from 10 AM to 10 PM, and there was much coding and learning done by all. There was a very powerful vibe shared by nearly everyone there, and it was great to see so many people from different personal and open source backgrounds working together and having a great time as a group. Filtering out distractions We made some changes to our proceedings for this event, entirely because last time with 'distractions' that caused some issues. In a nutshell, here is 50% of what we did: A clear statement in the event description and follow up emails that this event was for developers and designers only. Laptops were an absolute requirement for entry into the event. We also rolled in a couple other tricks I'm not going to write down. If you see me in person, ask away. The results were near perfect, and we won't hesitate to use these techniques again. Sponsors We let attendees know which sponsors were interested in potential … -
July 15th, 2012 LA Open Source Recap
On July 15th, 2012, at the July LA Hackathons Open Source event, over 60 Python, Django, Ruby, Ruby on Rails, PHP, JavaScript, Node.js, Perl, and Clojure developers arrived to work on a variety of projects. We went from 10 AM to 10 PM, and there was much coding and learning done by all. There was a very powerful vibe shared by nearly everyone there, and it was great to see so many people from different personal and open source backgrounds working together and having a great time as a group. Filtering out distractions We made some changes to our proceedings for this event, entirely because last time with 'distractions' that caused some issues. In a nutshell, here is 50% of what we did: A clear statement in the event description and follow up emails that this event was for developers and designers only. Laptops were an absolute requirement for entry into the event. We also rolled in a couple other tricks I'm not going to write down. If you see me in person, ask away. The results were near perfect, and we won't hesitate to use these techniques again. Sponsors We let attendees know which sponsors were interested in potential … -
DjangoCon videos and pictures
The DjangoCon videos have been online for a while now, but unfortunately without a download option. So for those that would like to download the videos, we've created a torrent with the full (raw) video material. You can find the torrent information in this gist.We also created a torrent for the pictures taken by our photographer. Again this is the "raw" material (meaning all the pictures, even the blurry ones, are included). Some photos have been removed because they showed potentially private content on laptop screens, other than that all pictures are included. The information about this torrent can be found in this gist.The material in both torrents is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.If you don't know how to download content via torrent, I suggest you try googling it, there should be more than enough information about this. -
How I Stopped Worrying and Started Loving PyLadies
When I read about PyLadies for the first time, my thoughts were a common knee-jerk: “separation is bad, dividing the community, …”. Like many of my privileged peers, I was pro-diversity but I thought this is the wrong way. My views changed over time and I filed it under “lessons learned”. Unfortunately, my old thinking patterns don’t cease to pop up in discussions, so I decided to share my perspective. First of all, let’s get one thing out of the way: Diversity is good for a community. If we can’t agree on this fact, you can stop reading here. There are enough studies and blog posts that support this point and if you’re not convinced, this article isn’t for you. If you look at it, this reason is pretty egoistic. But it seems the most helpful to make my point why you should care. The other question we should ask ourselves, is whether it isn’t our duty to help less-privileged ones (aka everyone who’s not a cis-gendered hetero white man in his twenties with a lot of free time) into our high-pay industry. But let’s keep social justice aside for now. In this article, I’m using women as the IT … -
Django Fundamentals Bootcamp Recap
On June 8th and 9th, Caktus hosted its first Django Fundamentals Bootcamp. The Caktus team developed the idea for the course, which was a crossword drill application, and has been developing the structure and content of the course over the past year. The bootcamp was designed to teach programmers who have experience in programming with ... -
Django Class-Based View Mixins: Part 1
-
Einladung zur Django-UserGroup Hamburg am 11. Juli
Das nächste Treffen der Django-UserGroup Hamburg findet am Mittwoch, den 11.07.2012 um 19:30 statt. Auch dieses Mal treffen wir uns in den Räumen der intosite GmbH im Poßmoorweg 1 (3.OG) in 22301 Hamburg. Da wir in den Räumlichkeiten einen Beamer zur Verfügung haben hat jeder Teilnehmer die Möglichkeit einen kurzen Vortrag (Format: Lightning Talks oder etwas länger) zu halten. Konkrete Vorträge ergeben sich erfahrungsgemäß vor Ort. Eingeladen ist wie immer jeder der Interesse hat sich mit anderen Djangonauten auszutauschen. Eine Anmeldung ist nicht erforderlich. Weitere Informationen über die UserGroup gibt auf unserer Webseite www.dughh.de. -
Simple HTTP Basic Auth Wall
I have a client who wanted their entire unlaunched public content site quickly but temporarily blocked for a short period of time. He wanted a universal password so he could send the site to reviewers, done quickly, and nothing else. In a few days the site will launch, and even if someone got through the authentication, nothing bad will happen except for an early visitor. So we determined this was a job for a very simple Basic access authentication implementation. I asked around and Jacob Kaplan-Moss gave me this awesome snippet using barrel that I pasted right into the bottom of the Django 1.4-style application's wsgi.py file. # Add to the bottom of your wsgi.py file # Don't forget to add barrel to your requirements! from barrel import cooper REALM = "PRIVATE" USERS = [('spam', 'eggs')] application = cooper.basicauth(users=USERS, realm=REALM)(get_wsgi_application()) This took all of 5 minutes to implement and launch. The result is that the first time you visit the site the login prompt appears. If you enter 'spam' and 'eggs' then you can see the site fine. It worked and the customer was happy. Will this block a concerted penetration attempt? Of course not. If the site has/had critical … -
Simple HTTP Basic Auth Wall
I have a client who wanted their entire unlaunched public content site quickly but temporarily blocked for a short period of time. He wanted a universal password so he could send the site to reviewers, done quickly, and nothing else. In a few days the site will launch, and even if someone got through the authentication, nothing bad will happen except for an early visitor. So we determined this was a job for a very simple Basic access authentication implementation. I asked around and Jacob Kaplan-Moss gave me this awesome snippet using barrel that I pasted right into the bottom of the Django 1.4-style application's wsgi.py file. # Add to the bottom of your wsgi.py file # Don't forget to add barrel to your requirements! from barrel import cooper REALM = "PRIVATE" USERS = [('spam', 'eggs')] application = cooper.basicauth(users=USERS, realm=REALM)(get_wsgi_application()) This took all of 5 minutes to implement and launch. The result is that the first time you visit the site the login prompt appears. If you enter 'spam' and 'eggs' then you can see the site fine. It worked and the customer was happy. Will this block a concerted penetration attempt? Of course not. If the site has/had critical … -
Rate your ISP
In June a bunch of great people went with me to a cottage for the weekend to create something. It was our 3rd Wilderness Labs adventure. The outcome is pretty awesome. We built a service to collect simple ISP reviews to help Canadians find their best local ISP. We called it RateMyISP. (Coming up with names might not be our strongest suit.) The idea came from Open Media's Stop the Meter campaign when more Canadians signed a petition protecting indy ISPs than use them. People who use the larger players still wanted the indy ISPs to exist so they would have an option when they become dissatisfied. Trouble is, finding the right local or indy ISP is kind of difficult. I found mine in London, ON thanks to a Reddit comment which is no doubt now buried never to be found again. The comment listed the local ISP options per city in southern Ontario. There had to be a better way and now there is. The service is ready to start absorbing reviews. As we gather reviews over the next few months we will use that information to vastly improve the search. We plan to highlight what areas indy ISPs …