Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Shortcutting render_to_response
render_to_response is [supposed to be] a shortcut. But when you are using RequestContext, you end up with lots of lines reading like this: render_to_response('template.html', variables_dict, context_instance=RequestContext(request)) I can type fast, but I don't like typing the same code again and again. Maybe I'm a DRY fanboy, but let's hope that's not the case. Over the last few months I've been using some techniques for avoiding typing context_instance=RequestContext(request) after every return statement, however I still haven't found the perfect one, since there's always a tradeoff between flexibility and the number of characters you have to type. So I think it's time to make an entry about it, get some feedback and post the results to django-dev. The most simple approach: wrapper function It's not pretty, nor pythonic, but it's simple and effective as hell. Just define a wrapper function and call render_to_response from it: def my_render(template, variables_dict, request): return render_to_response(template, variables_dict, context_instance=RequestContext(request)) The object oriented way: inheriting from HttpResponse This is one of my favourite approaches, since it doesn't depend on render_to_response. class RenderedResponse(HttpResponse): def __init__(self, template, request, items = {}, **kwargs): t = loader.get_template(template) super(RenderedResponse, self).__init__(t.render(RequestContext(request, items)), **kwargs) In addition, this lets you add some template caching very easily: class … -
About Django and the importance of releases
My favorite Python web framework, Django, has not been updated for a long time. The most current release, 0.96, was released in March 2007. This is a very long time, when you're in the market of web frameworks. This doesn't seem to bother a lot of people, as the common answer in the django community seems to be just to run the trunk version (development version). I for one doesn't like that solution. And here are some of the reasons why. Some of the problems with running a development version When a security release is made, I cannot just update, but need to merge the change in, in all of my installations. An update could maybe break my existing code with backward incompatible changes. It's easier to tell my co-workers that our projects will run 0.96, and not r6389 for one project and r7291 for another (+ a couple of security patches). That's okay if you are a single-person team working on a single project, but not when you have several people and projects. Developers are afraid to commit new things to trunk, because a lot of users will be disappointed when they eagerly update their repositories each morning just … -
About Django and the importance of releases
My favorite Python web framework, Django, has not been updated for a long time. The most current release, 0.96, was released in March 2007. This is a very long time, when you're in the market of web frameworks. This doesn't seem to bother a lot of people, as the common answer in the django community seems to be just to run the trunk version (development version). I for one doesn't like that solution. And here are some of the reasons why. Some of the problems with running a development version When a security release is made, I cannot just update, but need to merge the change in, in all of my installations. An update could maybe break my existing code with backward incompatible changes. It's easier to tell my co-workers that our projects will run 0.96, and not r6389 for one project and r7291 for another (+ a couple of security patches). That's okay if you are a single-person team working on a single project, but not when you have several people and projects. Developers are afraid to commit new things to trunk, because a lot of users will be disappointed when they eagerly update their repositories each morning just … -
django pluggables
I have struck goldmine ! Bored today with another plone innard hacking session I began hunting around on the internet for a django plugins site. I came across this site called http://www.djangoplugables.com/ ! This is exactly what I am looking for with a cute little plug in socket as a logo! I am astounded by the speed in which django has grown ! I have coded some applications with django the past and I can say I like the feel of using it. It is has what I need in terms of a web application framework and is closer to the python metal than plone or zope will ever hope to be. Don't get me wrong, I still have a soft spot for zope and I truly hope that zope 3's modularity will be more elegant than the monolithic monstrosity that zope 2.x is.Today while looking at the pluggable site, has given me much more confidence of adopting django as one of the stable technologies to deliver web applications in my company's offerings. Coming from a background that have used both I can attest to why a senior python programmer would love django. I hope though the django community get … -
Distribuindo tabelas MySQL em vários servidores
Os frameworks para desenvolvimento web como o Django possuem um ótimo ORM, facilitando muito a criação de aplicações rápidas e eficientes. Da mesma forma que facilita o desenvolvimento, atrapalha em alguns pontos, como por exemplo se o desenvolvedor desejar utilizar mais de um banco de dados para a mesma aplicação. Embora seja possível fazer, as [...] -
StaticGenerator for Django Updated (1.3.1)
Version 1.3.1 of StaticGenerator is out. You can now get it using easy_install. The big news is that StaticGenerator now leverages Django’s awesome Middleware system to more efficiently create the static files. -
Django Meetup Postmortem
Thanks to the organizer Jannis, last Friday German djangoers met successfully, got some beer at Schleusenkrug in Tiergarten, Berlin, and became better aquainted with each other. We discussed the latest actualities like licenses, project deployment, business models, the future of Django, who from the gods of Django said what in which blog, and other geeky stuff.If you want to get in touch with German djangoers, you can join the #django-de IRC channel on irc.freenode.net. Also you can subscribe to their blogs at django-de.org. -
DjangoSites is 1337
It's kind of nerdy and geeky, but we've just passed the 1337th approved site on DjangoSites. The lucky submission was Chinet, the website for a set of environmentally friendly disposable tableware. From glancing at the websites as they're approved, I'm noticing the quality of design of many websites improving compared to the more 'tech-friendly' submissions when the project first began. It's a great sign that Django is reaching further into everyday website development, which can only mean good things. Here's to another 1000+ sites! -
DjangoSites is 1337
It's kind of nerdy and geeky, but we've just passed the 1337th approved site on DjangoSites. The lucky submission was Chinet, the website for a set of environmentally friendly disposable tableware. From glancing at the websites as they're approved, I'm noticing the quality of design of many websites improving compared … -
Readout of TypoScript with eID and BE-Modul
Sometimes you have to get TypoScript values in different places. The following will illustrate two problems that proved me. TypoScript with eID The script being called via eID is kind of lightweight and does not load a fully features TYPO3 core. User as well as database are initialized quickly but if you want to use values from TypoScript this unfortunately cannot be achieved with two lines of code. You at least need to transfer the page id to the eID script - I'm using a GET variable - to correctly initialize the TSFE. Then just instantiate a tslib_fe class, connect to the database, initialize the user, template and config and you're done: // eID specific initialization of user and database tslib_eidtools::connectDB(); tslib_eidtools::initFeUser(); // initialize TSFE require_once(PATH_tslib.'class.tslib_fe.php'); require_once(PATH_t3lib.'class.t3lib_page.php'); $temp_TSFEclassName = t3lib_div::makeInstanceClassName('tslib_fe'); $GLOBALS['TSFE'] = new $temp_TSFEclassName($TYPO3_CONF_VARS, $pid, 0, true); $GLOBALS['TSFE']->connectToDB(); $GLOBALS['TSFE']->initFEuser(); $GLOBALS['TSFE']->determineId(); $GLOBALS['TSFE']->getCompressedTCarray(); $GLOBALS['TSFE']->initTemplate(); $GLOBALS['TSFE']->getConfigArray(); Now access the data in the well-known way: $GLOBALS['TSFE']->tmpl->setup['plugin.']['extensionkey.']['your_value'] By the way: with this line of code you can readout the TypoScript in not fully initialized plugins, too. TypoScript in backend modules Sometimes there is the necessity to access TypoScript in backend modules, e.g. when sending an email to readout the sender. The process is similiar to … -
Readout of TypoScript with eID and BE-Modul
Sometimes you have to get TypoScript values in different places. The following will illustrate two problems that proved me. TypoScript with eID The script being called via eID is kind of lightweight and does not load a fully features TYPO3 core. User as well as database are initialized quickly but if you want to use values from TypoScript this unfortunately cannot be achieved with two lines of code. You at least need to transfer the page id to the eID script - I'm using a GET variable - to correctly initialize the TSFE. Then just instantiate a tslib_fe class, connect to the database, initialize the user, template and config and you're done: // eID specific initialization of user and database tslib_eidtools::connectDB(); tslib_eidtools::initFeUser(); // initialize TSFE require_once(PATH_tslib.'class.tslib_fe.php'); require_once(PATH_t3lib.'class.t3lib_page.php'); $temp_TSFEclassName = t3lib_div::makeInstanceClassName('tslib_fe'); $GLOBALS['TSFE'] = new $temp_TSFEclassName($TYPO3_CONF_VARS, $pid, 0, true); $GLOBALS['TSFE']->connectToDB(); $GLOBALS['TSFE']->initFEuser(); $GLOBALS['TSFE']->determineId(); $GLOBALS['TSFE']->getCompressedTCarray(); $GLOBALS['TSFE']->initTemplate(); $GLOBALS['TSFE']->getConfigArray(); Now access the data in the well-known way: $GLOBALS['TSFE']->tmpl->setup['plugin.']['extensionkey.']['your_value'] By the way: with this line of code you can readout the TypoScript in not fully initialized plugins, too. TypoScript in backend modules Sometimes there is the necessity to access TypoScript in backend modules, e.g. when sending an email to readout the sender. The process is similiar to … -
Readout of TypoScript with eID and BE-Modul
Sometimes you have to get TypoScript values in different places. The following will illustrate two problems that proved me. TypoScript with eID The script being called via eID is kind of lightweight and does not load a fully features TYPO3 core. User as well as database are initialized quickly but if you want to use values from TypoScript this unfortunately cannot be achieved with two lines of code. You at least need to transfer the page id to the eID script - I'm using a GET variable - to correctly initialize the TSFE. Then just instantiate a tslib_fe class, connect to the database, initialize the user, template and config and you're done: // eID specific initialization of user and database tslib_eidtools::connectDB(); tslib_eidtools::initFeUser(); // initialize TSFE require_once(PATH_tslib.'class.tslib_fe.php'); require_once(PATH_t3lib.'class.t3lib_page.php'); $temp_TSFEclassName = t3lib_div::makeInstanceClassName('tslib_fe'); $GLOBALS['TSFE'] = new $temp_TSFEclassName($TYPO3_CONF_VARS, $pid, 0, true); $GLOBALS['TSFE']->connectToDB(); $GLOBALS['TSFE']->initFEuser(); $GLOBALS['TSFE']->determineId(); $GLOBALS['TSFE']->getCompressedTCarray(); $GLOBALS['TSFE']->initTemplate(); $GLOBALS['TSFE']->getConfigArray(); Now access the data in the well-known way: $GLOBALS['TSFE']->tmpl->setup['plugin.']['extensionkey.']['your_value'] By the way: with this line of code you can readout the TypoScript in not fully initialized plugins, too. TypoScript in backend modules Sometimes there is the necessity to access TypoScript in backend modules, e.g. when sending an email to readout the sender. The process is similiar to … -
Django Meetup at Linuxtag
Pssst. Don't tell anybody! There is an unofficial Django user meetup happening in Berlin this Friday at five. datetime.datetime(2008, 5, 27, 17, 0)The gathering point is at the main entrance of Linuxtag conference (Messe Berlin). -
Double-Edged Swap
At Slicehost, users occasionally enter our chat to complain that their Slice has suddenly come to a crawl. In nearly every occurrence of this behavior the underlying cause of the slowdown is consistent swapping. And in nearly every occurrence of consistent swapping, the culprit is Apache. -
How to dive into another team’s Django code
I’m starting to learn my way around another team’s Django project. They started from yet another team’s code base, and extensively modified it over the last ~1.5 years. It’s code for a large commercial site, which I hope to use to build an even larger commercial site having needs similar to, but different from, theirs. My immediate goals are [...] -
Hacking Contributed Models
Django comes with a bunch of contributed applications like auth for authentication, admin for basic data manipulation, or flatpages for the dynamic content that tends to be rarely changed. Sometimes you want to use them, but their functionality doesn't completely fit your needs.You have several options in that case:Use custom models with one-to-one or many-to-one relations, creating extensions for existing models. The main drawback of this approach is that those custom models will be editable in the contributed administration separately from the origin or you will need to create custom views to combine everything nicely.Use modified duplicates instead of the contributed applications. The main drawback of this case is that it will be hard to manage the updates of the models.Use signals to modify the models. This can be too complicated for simple changes.Modify the properties of the models on the fly.Let's dig deeper into the last option. When you start the shell or request for a page on the web server, at first Django loads all modules according the order of the INSTALLED_APPS setting. As Python is an interpreted language and all methods and properties are public, you can access and change them on the fly.For example, if your … -
Tips #2
What time is it now? It's time to give you some more tips about Django development!Use batch scripts to automate manual routines. Do not repeat yourself extracting and compiling translatable strings, starting and stopping development web-servers, updating and committing your project to the version-control system in the console. Write batch scripts which you can run within one mouse click instead.Define overwritable constants in your applications. Your applications are likely using some values that might be defined as constant values, i.e. the dimensions for avatars of users. Define those constants so, that you could overwrite them in the project settings if necessary. from django.conf import settingsSOME_SETTING = getattr(settings, "SOME_SETTING", "default value")Have one view for site-related JavaScript globals. Django views usually return (X)HTML-based responses, but it can return XML, JavaScript or others as well. Usually you will hold all you JavaScript functions in static files, but there might be some situation, where you need to get information related to database or project settings, for example, the MEDIA_URL.The following view might be used to display a javascript page directly from a template. Just pass the template to the view in your urls.py file.from datetime import datetime, timedeltafrom django.views.generic.simple import direct_to_templatedef direct_to_js_template(request, *args, **kwargs): … -
DRY While Working With Choices for Forms
When creating dozens of forms with selection fields for some many-to-one or many-to-many relations, you might find that it's ineffective to create choices for the form fields from querysets formed by the relations defined by ForeignKeys and ManyToManyFields. You have to import the related models, filter the choices analogously to the limit_choices_to parameter, and form a list of tuples again and again.To get the same choices from the model as in the admin form, you can use the following:FIELD_CHOICES = SomeModel._meta.get_field("field_name").get_choices()Then you can modify the text for the null-value choice, likeFIELD_CHOICES[0] = ("" _("- Choose One -"))or even remove it:del FIELD_CHOICES[0]To save the selected object you can simply assign the chosen value to the foreign key, like:new_instance = SomeModel()new_instance.field_name_id = form.cleaned_data['field_name']new_instance.save()If you need to do something with the selected object, you can still live without importing specific models and filtering the entries in the same manner as limit_choices_to. To save time, you can use the following function, which returns the queryset containing all the choosable objects:def get_related_queryset(model, field_name): """ Get the queryset for the choices of the field in a model Example: objects = get_related_queryset(SomeModel, "field_name") """ f = model._meta.get_field(field_name) qs = f.rel.to._default_manager.complex_filter(f.rel.limit_choices_to) return qsJust put this function in one … -
Django-treemenus new release 0.4
I have just released the version 0.4 of django-treemenus It does not contain code modifications so you don’t necessarily have to upgrade if you’re currently using it. In fact, this release integrates more languages, so you may be interested if you’re not happy with the standard English version. Thank you to Maxim Oransky for marking a couple of missing strings and for providing the Russian translation. Thank you also to Ido Sebastiaan van Oostveen for providing the Dutch translation. I’ve also added French locale, so that’s now 4 languages including English. Please send me your translations in other languages and I’ll integrate them in future releases. Django-treemenus has been quite stable it seems since the last release. I use it in several projects, and my clients like it simplicity of use (in particular the user-friendly representation of the tree structure in the admin). I’d be happy to hear more feedback, so please let me know how you use this, if you’ve extended or improved it. Any suggestion or testimonial is very welcome! Finally, a couple of things I’m planning to work on in the near future: handle caching and better integration with newforms-admin. -
DjangoProjectLauncher?
I just filed a ticket with the Google AppEngine project requesting the source to GoogleAppEngineLauncher, with the idea that this would make a very cool Django developer's aid on OS X -- much like Locomotive for Rails. Anybody else interested in this should go star it: http://code.google.com/p/googleappengine/issues/detail?id=386 Update: Cool. In less than 24 hours, 38 people have starred the issue, making it the 31st most-requested item and rising -- ahead of hot numbers like "Please add Tcl support". Sorry, Tcl. -
How Do You Fight Spam?
In the last few weeks I’ve been getting an increasingly amount of comment spam. This was expected though — I’ve done nothing to actually keep spam out. For a tiny blog like mine I feel the two traditional ways of blocking spam; user registration and CAPTCHAs, are not very user friendly. As a first line of defense I decided to disable commenting for posts older than 2 weeks. As always with Django, it turned out to be much simpler than I thought. Step 1: Create a template filter The template filter is very straight forward. It takes a date and returns True/False if the date is within 14 days. I hardcoded the limit to 14 days in my example, however it should probably be an setting in settings.py. If you do not know or remember how to create a template filter, Django has some excellent documentation on the subject. 1 2 3 4 5 6 7 8 9 10 11 12 13from django import template import datetime register = template.Library() @register.filter def showcomments( date ): date_adjusted = date + datetime.timedelta( days=14 ) if datetime.datetime.now() <= date_adjusted: return True return False Step 2: Modify the blog template In your blog post template add an if statement … -
Garść nowości.
Trochę informacji na temat co się dzieje w świecie Django. Dodatkowe opcje dla funkcji 'update' w nowym ORM-ie Sebastian Noack napisał rozszerzenie funkcjonalności funkcji update. Dotychczas mogliśmy podać tam tylko stałe wartości (np. foo=42). Z jego rozszerzeniem możemy podać całe... -
Pocket Django
At the Western Mass. Developers Group meeting this week I showed a few people some of the unixy fun you can have with a (jailbroken) iPod touch and the Cydia package manager. Cydia is a port of Debian's APT system to the iPhone platform -- i.e. it's a real package manager. It made it a snap to install Python, Mobile Terminal, Mobile Text Edit, Subversion, etc. This is the toolset that has allowed me to even do some work on the book as I mentioned in my last post. And while it has its limitations as a development environment, of course I did get Django running on it. Below are a couple screenshots of an example application from the book. This is my kind of portable computer! -
Web frameworks: a free software oriented study
The web2.0 era has put the web application frameworks at the center of the free software (aka FLOSS) community attention. Various opinions (1,2) and performance (1,2) comparisons have been published by free software enthusiasts trying to rank the quality and the potential of different web frameworks. In this post we use standard data mining and [...] -
Django OperationalError Debugging
So on one of our test servers I was doing some heavy performance testing when I noticed a strange OperationalError exception message in the Debug console for Django: I went digging around and sure enough I had all kinds of locks when I attempted: mysql> SHOW PROCESSLIST; So next I checked the status of the free space available to learn than the partition that the mysql data was on was completely full. So, shutdown mysql and relocated the data to another partition with plenty of room: mysqladmin shutdown mv /usr/local/apache/var/* /new/location/for/files/ Then I changed /etc/my.cnf so that it had the following lines edited or amended: [mysqld_safe] datadir = /new/location/for/files/ Make sure that the ib_logfile files don't remain in the new location: rm /new/location/for/files/ib_logfile* Now restart mysql and verify that everything is working: mysqld_safe & echo "create database testdatabase;" | mysql echo "show databases;" | mysql