Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django site permissions
I’m announcing Site permissions, django application that allows restricting access to objects based on which site they belong. Basic goal is to allow restrict managing site content to users and groups in django admin interface. Site permissions works on and depends on django-guardian. Source code and example app is available on githib: https://github.com/bmihelac/django-site-permissions -
Handy mod_wsgi process names
One of the reasons I started experimenting with gunicorn instead of mod_wsgi was that it would help me identify the sites when looking at cpu/memory usage with top. With standard apache+mod_wsgi, you only get line upon line of /usr/sbin/apache2 -k start with no indication of which site it actually is. Turns out mod_wsgi can do that just fine, too! I got a comment on my gunicorn blogpost from Diederik v/d Boor that told me about mod_wsgi's display-name option. It was right there in mod_wsgi's WSGIDaemonProcess documentation but I completely overlooked it. What I did was to add a display-name like this: WSGIDaemonProcess mysite display-name=mysite_wsgi user=xyz group=xyz In top you might have to press c to view the full commandline for every top line. (Tip: press W to write the top config to disk to persist the change). See this picture. It shows a couple of not-yet converted wsgi sites with the unhelpful /user/sbin/apache2 name and a couple with the sitename with _wsgi in it. -
Leverage browser caching in Django and Lighttpd
An easy optimisation that greatly improves your website’s speed is to leverage browser caching through appropriate HTTP response headers for static files (CSS, images, JavaScript, etc.). My favourite technique is to set long expiration timestamps and then to force browsers to reload updated static content by a slight change in the file path. This technique is fairly easy to set up in Django and Lighttpd. -
Single simple view for Django form processing
I always feel a bit dissatisfied with the amount of code I have to put in to process forms in Django views. Like most python developers it feels like I've gotten too complex it if takes me more than 5 or 6 lines of code to do something. Previously I had coded seperate create and update views for form processing, partially this was to better control permissions but also because of the differences in dealing with bound and unbound forms as well as model instances. This is my first stab at implementing that simple logic based on several examples I've seen out there in other blogs. @login_required def post_edit(request, id=None): """ Handles creating or updating of individual blog posts. :parm request: request object being sent to the view. :param id: post id, defaults to None if new post. """ instance = None if id: instance = get_object_or_404(Post, id=id) title = "Create New Post" if instance: title = "Editing Post" # Create the form as needed. form = PostForm(request.POST or None, instance=instance) # Didn't work for me unles I passed k,v pair in instance. # Save the edited form if needed if request.method == 'POST' and form.is_valid(): # Validate and … -
I don’t like Django class-based generic views.
Django had function-based generic views through version 1.25. They were replaced in version 1.3 by class-based generic views. Some caveats: I’m not the sharpest knife in the drawer. I’m not FSM’s gift to web development. I have a lot of experience with the function-based generic views, and little experience with the class-based ones. (Because they’re new. Duh.) From yesterday’s experience, the new generic views use a very powerful but excessively complicated abstraction. I can only symptomatically describe the problem and I don’t have a good answer, but this is my blog so I’m going to bitch about it. If you don’t agree then move along, these aren’t the droids you’re looking for. My task was simple: Code a, “display detail about an object,” page. The object is a db table row. That’s all. After two hours, I wanted to stab my eyes with live yellow jackets. I wanted this page accessible to only logged-in users, so I needed to override as_view() and use @login_required(). I also needed one of our decorators to verify that the user owned the db row. And, of course, I had to pass the db row object (from a Foobar.objects.get(yadda yadda yadda) call) to the as_view(). … -
Reading Site Domain into Django Templates
There are a number of great new features in Django 1.3 for template developers. Not the least of which is the addition of the STATIC_URL attribute in settings.py to help with referencing static media. I found when trying to integrate social media linking in blog posts however that there wasn't a good way to pull the entire site domain into a URL without hard coding into the template. Something that makes and descent Django developer shiver. The easiest way around this is to use the .get_current() method of the Site model and access that via a custom template tag in your templates. The code itself is very simple: from django import template from django.contrib.sites.models import Site register = template.Library() @register.simple_tag def sitedomain(): '''Returns the URL of the default site.''' try: return Site.objects.get_current().domain except Site.DoesNotExist: return None This makes it pretty easy to call in your template. I was able to use it to forward complete URLs onto some javascript functions that provides social linking in posts. -
New handy blog from a colleague
One of my colleagues regularly sends out an email to us with a couple of nice javascript or python packages he noticed online. Or handy websites. I like getting those, as it is an extra source of input and inspiration. Since two days or so he's got a blog. And he's apparently decided to do the company-internal-email thingy on his blog, too. Lots of potential to be a useful resource, I'd say. Two examples: Literate programming. Interactivity in mapping apps. Check it out at http://weblog.nyholt.nl . -
Two useful enhancements for Django Debug Toolbar
Sometimes on my work I experience two typical issues: first one is that on unknown projects I don't know what objects was changes, how much objects was changed and what is deleted. To find out what's going on the current page(s) I have to study code of views, internal methods etc. Sometimes it's really pain in the ass, for example if I work on satchmo-based projects.Another typical issue is hard way to keep valid HTML during long-term development. I don't want to add plugins to my browser which will validate my html. But I still need to develop clean and transparent HTML code. So I made decision to develop additional HTML Validator panel for Django Debug Toolbar.Past month I've done two panels (screenshots below):State Debug Panel – debug_toolbar.panels.state.StateDebugPanelHTML Validator Debug Panel – debug_toolbar.panels.htmlvalidator.HTMLValidationDebugPanelAll of the code was merged with current master of django-debug-panel and available on github -
Caching web sites and web applications…
…Why, Where, What and How of caching web sites Basics of web page load: Every time when you open an webpage this results in a series of requests and responses between the client(your browser) and the web server that hosts the requested sites(most of the times this includes more the one servers). Each request tells [...] -
Python on Android, Django Unit Testing at OPAG
Ottawa Python Authors Group meeting tomorrow Thursday May 26 at 8p.m. Best of all it's not me talking this time! Hope you can make it out. -
A REST wankery question
Consider a simple photo storage service as an API. Users can only interact with the API if they’ve got an account. Let’s say authorization happens over HTTP Basic. Given that, would you use URIs like /photos and /photos/{id} (as a photo list and photo detail resource, respectively)? What’s weird about those URIs is that my /photos is a different list of photos than your /photos – in other words, the resource represented depends on the information in the Authorization header. -
Gunicorn zero-length bug fixed
Two weeks ago I wrote about a zero-length bug I encountered with gunicorn when running it under apache in certain cases and when using internet explorer. Corner case, but still. With some apache tweaking I managed to work around it (or solve it). I submitted a bug report suggesting a small doc update for this corner case and got a quick reply from the author asking me to try out the most recent release, as that apparently contained an fix for "chunked encoding". I hooked 0.12.2 up into my site instead of the 0.12.1 that I was using and yes, it fixes it! So hurray for open source and responsive authors! -
Django Models Mixins
One thing I've been experimenting with is model Mixins. For example, the aim is to create small abstract classes that are each focused around a particular function. These abstract classes can then be added to arbitrary models to apply those functions to models as desired.For example, say I define a RatingsFields abstract class and a TrackingFields abstract class. These abstract classes can be mixed into any other model that we wish to add rating or tracking functionality to. core/mixins.pyfrom djangoratings.fields import RatingField # 3rd party moduleclass RatingFields(models.Model): rating = RatingField(range=5) # 5 possible rating values, 1-5 class Meta: abstract = True class TrackingFields(models.Model): deleted_on = models.DateTimeField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Meta: abstract = True Since we applied the abstract classes to the Post model below, the model now has rating and tracking capabilities. This is useful to help simplify code where a lot of models share fields or methods with the same function.myapp/models.pyfrom core import mixins as core_mixinsclass Post(core_mixins.TrackingFields, core_mixins.RatingFields): name = models.CharField(max_length=128) slug = models.SlugField(max_length=128) ...Comments welcome.Joe -
Comentário sobre Configurando um projeto Django no UOL Host – segunda parte por Valder
Guilherme, o download via git/svn por FTP é impossível. O que vc pode fazer é fazer isso em sua máquina e mandar por ftp para o servidor da UOL. O que dá para fazer e testar uma estrutura de diretórios diferentes da do tutorial. Algo como: public_html/Django public_html/meu_projeto public_html/.htaccess Ai no .htaccess vc manda o PYTHONPATH para o public_html/Django;public_html/meu_projeto Não fiz os testes, mas acho que é possível. Já que o apache não vai ligar para os exports, ele apenas enxerga as informações do .htaccess SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE meu_projeto.settings PythonInterpreter meu_projeto PythonOption django.root /meu_projeto PythonDebug On PythonPath "['/home/valdergall/public_html','/home/valdergall/public_html/Django'] + sys.path" Acho que se vc jogar o diretório que contém do diretório django que fica dentro do Django direto no public_html nem precisa ter 2 caminhos no python path. Mas eu não tenho certeza se vai funcionar. Outra opção é usar o virtualenv para o seu próprio ambiente de projeto e jogar todo o envproject no public_html. -
Comentário sobre Configurando um projeto Django no UOL Host – segunda parte por Guilherme
E pra quem tem serivço de revenda e não tem acesso via ssh para fazer o download via trunk/git/svn o que fazemos? Já tentei o processo que o suporte recomendou copiar a pasta do projeto para uma pasta (public_html/meuprojeto) e colocar dentro dela o arquivo .htaccess isso está certo? não deu certo comigo. Tem outra solução? -
Audio recording in Django apps with flvar
flvar is a flash applet working with a media server and allows users to record audio clips on a website using it. To use it in a Django project you need to setup the media server like Red5, and map some hardcoded paths in flvar recorder to Django views and templates. -
Getting Django to work with uWSGI on Cherokee
* Installing uWSGI * Creating uwsgi.conf file /home/emilian/springmerchant dev.django_wsgi * -
CouchDB + Django + Couchdbkit
CouchDB + Django + Couchdbkit -
CouchDB + Django + Couchdbkit
Just some notes for future use. Couchdbkit: Searching by key: Document.view('document/all', key='') -
The state of python and the web - Armin Ronacher (PyGrunn conference)
Armin's a founding member of the pocoo team with projects like jinja2, werkzeug, sphinx and so. Python 3 is the elephant in the room that nobody's talking about. There's a lot of python 2 code and porting is turning out to be harder than expected. Some recent python developments: Unladen swallow is "resting". Development stopped. It was the number one hope to make python faster. Python 3.2 got released. Python's packaging is being worked on a lot. Pypy turns out to be quite fast nowadays. Really really fast. What's pypy? It is python written in python. Well, in "restricted python", which can be translated to C automatically. It is 3.7 till 40 times faster than regular cpython!!! Things that will work? Django, flask, pyglet, twisted, sqlite, ctypes and so on. A problem with pypy is that there's only experimental support for the python C API. And C-level extensions will always be slow. And there is no reference counting, so you need (for instance) to close files yourself. But, in summary, python 3 is where all the new language development is happening. What does python 3 mean? Unicode cleanup. All text-like things are either unicode text or a binary blob. The … -
The ten commands of security - Jobert Abma (PyGrunn conference)
He's an ethical hacker at online24, hacking SME and government websites as a job. Some items to keep in mind regarding security. Your application isn't the only attack vector. Your app is on a server. Who has access to that server? Which other apps run on that server? And the bigger the organization, the more chances for "social engineering": for instance mimicking an employee and asking for a password for xyz. Conduct risk assessments to identify risks. Identify the risks, only then can you take action on them. Rate your identified risks. Only trust your own code. And double check. It is not OK to rely implicitly on the underlying platform. Something that can solve a lot of major issues: security by design. Design it in. Centralize certain processes like validation or authentication and make them secure. Always be aware of technical issues. If you catch errors, make sure you know when something goes wrong because of catching the errors, for instance. Time (mis)management is a big problem. If you don't have enough time to properly do security, you'll have problems. Jobert thinks the big playstation hack was a security risk they were aware of, but just didn't have/got the … -
Redis in practice - Pieter Noordhuis (PyGrunn conference)
Pieter works on the core of Redis. The core is just two people, but still :-) So it was fun to have him give a talk here at this conference. Redis is "an advanced key/value store". You probably have heard of memcached. It is also a key/value store. Redis is something similar, but it has more data types. Memcached only stores blobs, redis also has lists, sets, etc. Redis stores everything in memory, so it is blindingly fast. Single thread, so just fire up multiple intsances if you've got more cores. Unlike memcached, you can persist it to disk. Replication is build-in. And it has client libraries for some 20 languages. Redis has build-in expiry. Just explicitly set the expiration time, no need to keep track of expiration yourself. Regarding lists, redis shows why it is more advanced than other non-datatype key/value stores: it supports pushing and popping at the begin and end of lists. You can use this for instance for showing recent events on some dashboard. Or a twitter-like timeline. To prevent these lists from becoming too big, you can tell redis to limit the length to a certain number. Now multiple clients can add items to the … -
Lightweight python deployment servers - Luit van Drongelen (PyGrunn conference)
He's mainly going to talk about uWsgi. He's especially not going to talk about apache :-) (Most in the audience were still using mod_wsgi + apache, btw). The reason he got involved with lightweight python servers as he's got a small hobby server only, so running apache with a couple of apps on a 256Mb memory server isn't fun. What's wrong with apache? By using ngnix for your static files you can easily double the response rate for a much lower memory usage than with apache. Ngnix can natively connect to uWsgi and apache cannot. uWsgi is fast and self-healing and sysadmin-friendly. It runs everwhere except on windows. It is more performant and has a lower memory footprint than mod_wsgi. Handy: it can handle multiple python interpreters, also in multiple virtualenvs. Very handy: it kills off misbehaving worker threads so that such a thread doesn't bring your entire server down. uWsgi can do more at the moment. It isn't wsgi-only anymore. It can handle long-running tasks for you if needed. If needed, you can run it with its own build-in webserver for testing purposes. And there's support for clustering. According to him, uWsgi has the best feature set of the … -
Practical project automation
I got a request for repeating an earlier talk about practical project automation at the PyGrunn conference. A conference in Groningen in the north of the Netherlands about python and related subjects. Sounded great, so I set out to update the talk. The basic structure could remain intact, as I'm still practicing what I preached at that older talk even though I'm at a new job right now. So it is really valid :-) Projects are more than just a collection of code. Projects are important. Projects are only finished when they're deployed. On the server so that the website is visible to the customer, for instance. Or installed on the customer's laptop. So one way or another you'll have to grab together all the pieces and install it somewhere. But you also have to do that yourself on your development laptop, right? And your colleagues, too. How many pages of instructions do you want to give to your colleagues? You'd better be automating this! And... automation helps heaps regarding quality. The cobbler's children go barefoot. We write software for our clients, but our own processes are non-automated manual and menial steps. Menial is bad, as it is boring. So … -
Class-based generic views and date evaluation in Django 1.3
Django 1.3 introduces class-based generic views as a replacement for function-based generic views. This new feature provides a more elegant solution to the long-standing issue of date evaluation in urls.py.