Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
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 … -
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! -
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... -
AOP aspect of JavaScript with Dojo
Finally: my open source JavaScript project DCL is built on ideas described in this article. Available for node.js and modern browsers, it implements OOP with mixins and AOP at "class" and object level. Read documentation and background articles on www.dcljs.org , clone its code on github.com/uhop/dcl , and follow @dcl_js . If we look at the history of computer programming languages, we can see that practically all new programming methodologies were about one thing: taming complexity. The anarchy of earlier days of procedural programming (example: Fortran) gave way to structured programming (Pascal), which was refined with modular programming (Modula), and was reformulated when object-oriented programing went mainstream (C++, and much later Java). And it stopped there. The focus shifted to different branches of computer programming, namely to functional programming, and, to a lesser degree, logical programming. The only major development in this branch was the rise of aspect-oriented programming (AOP) paradigm. Let’s take a look at AOP in our favorite language: JavaScript, and how Dojo helps the language with dojox.lang.aspect package. -
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 -
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 -
MySQL, Dates and Time zones, Postgres and Mindshare
A database can’t be all things to everyone. Each one has its sweet spot. MySQL happens to be the Wal-Mart of the database world. A large market sweet spot with lots of really cheap stuff, questionably good for you and serving a basic need. Occasionally, MySQL will let you down with some basic things… like time zones. When you store a date/time, it's often (but not always) important to store the time zone information that came with it. If you think about it, it's not just useful to know it's 1:00pm when you're trying to calculate temporal differences between two dates. You need to know what time zone the date was for. You can just convert the date/time to the local time but then you lose the time zone that was associated with the date originally. A piece of information forever lost! If you always have a time zone associated with a date/time, then importing and calculating dates across multiple time zones is incredibly simple. If not, you have to make assumptions about the time zones that can be confusing and very error prone. But? Does MySQL blend? Dates and time zones that is. MySQL doesn't handle time zones correctly. … -
Default arguments in Python: two easy blunders
I’m glad I stumbled across Patrick Altman’s tweet about a “default bug in Django“. I’d never have guessed you can pass a callable to a field’s default= argument, otherwise. That’s quite a powerful idiom, and I think I’ll use it a lot. To balance the karma, I’d like to post a quick reminder to everyone else that expressions in default arguments are calculated when the function is defined, not when it’s called. In Patrick’s code, for example, all objects created in the same running session got the same timestamp. Try this in the Python interactive prompt: >>>import time >>> def report(when=time.time()): ... print when ... >>> report() 1210294387.19 >>> time.sleep(5) >>> report() 1210294387.19 Until the interpreter quits, you’ll always get the same timestamp. The correct way to go about this is to default to None or some other sentinel, then replace it inside the function: >>> def report(when=None): ... if when is None: ... when = time.time() ... print when ... >>> report() 1210294762.29 >>> time.sleep(5) >>> report() 1210294772.23 Now that you know about that blunder, you should be able to figure out what’s going on with this second classic blunder when using default arguments in Python: >>> def spam(eggs=[]): …