Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
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 -
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=[]): … -
A Default Bug in Django
Not to say that this is a bug in django but rather a bug in how I had written some of my models. Just wanted to point out a quick tip for anyone else who may have done the same thing as me as well as for any of the django experts out there that might suggest a better way. What was happening was that I began to notice a wild discreptancy between two datetime columns in several models. They should have been identical, however, they were both getting their dates differently: ... date_column_one = models.DateTimeField(default=datetime.now()) date_column_two = models.DateTimeField(auto_now_add=True) ... What seems to be happening with this configuration is that datetime.now() is executed once when the server starts (and/or the module is imported) instead of what I thought would happen when I initially wrote these and that datetime.now() would get executed anytime an instance of the model was created and saved as a new record. My solution was to override the save method: ... date_column_one = models.DateTimeField() ... def save(self): if not self.id: self.date_column_one = datetime.now() super(MyModel, self).save() ... I am sure there is probably a better way and if you know of one, please leave a comment or send … -
A Default Bug in Django
Not to say that this is a bug in django but rather a bug in how I had written some of my models. Just wanted to point out a quick tip for anyone else who may have done the same thing as me as well as for any of the django experts out there that might suggest a better way. What was happening was that I began to notice a wild discreptancy between two datetime columns in several models. They should have been identical, however, they were both getting their dates differently: ... date_column_one = models.DateTimeField(default=datetime.now()) date_column_two = models.DateTimeField(auto_now_add=True) ... What seems to be happening with this configuration is that datetime.now() is executed once when the server starts (and/or the module is imported) instead of what I thought would happen when I initially wrote these and that datetime.now() would get executed anytime an instance of the model was created and saved as a new record. My solution was to override the save method: ... date_column_one = models.DateTimeField() ... def save(self): if not self.id: self.date_column_one = datetime.now() super(MyModel, self).save() ... I am sure there is probably a better way and if you know of one, please leave a comment or send … -
A Default Bug in Django
Not to say that this is a bug in django but rather a bug in how I had written some of my models. Just wanted to point out a quick tip for anyone else who may have done the same thing as me as well as for any of the django experts out there that might suggest a better way. What was happening was that I began to notice a wild discreptancy between two datetime columns in several models. They should have been identical, however, they were both getting their dates differently: ... date_column_one = models.DateTimeField(default=datetime.now()) date_column_two = models.DateTimeField(auto_now_add=True) ... What seems to be happening with this configuration is that datetime.now() is executed once when the server starts (and/or the module is imported) instead of what I thought would happen when I initially wrote these and that datetime.now() would get executed anytime an instance of the model was created and saved as a new record. My solution was to override the save method: ... date_column_one = models.DateTimeField() ... def save(self): if not self.id: self.date_column_one = datetime.now() super(MyModel, self).save() ... I am sure there is probably a better way and if you know of one, please leave a comment or send … -
Update to django-ae-utils
I’ve been hanging out at the NYC App Engine Hackathon today and I’ve had some time to work on django-ae-utils. Accordingly I’ve just posted an update to django-ae-utils. This update includes a User model which uses the App Engine datastore as a backend, as well as a few generic views for working with the model. [...] -
Extra
Después del fin de semana laaargo, en el cual me desconecte de la red y solo interactue en el "mundo real", llegué hoy a mi universidad y me di cuenta que la gente de google me envio un correo, solo para decirme que ya me habilitaron la cuenta de Google App Engine, ahora a hechar codigo!!! -
Mondrian & ReviewBoard
Word is that the a version of the code review tool that Google uses internally (called Mondrian) on the Google App Engine – called Code Review. I remember first seeing the Google tech talk on Mondrian and thinking that was … Continue reading → -
Django Templates: Good for so much more than HTML
I’m a big fan of Jon Bentley, the author of Programming Pearls. In this book, he discusses elegant solutions to problems that have irritated programmers for years. (I was in Europe for 6 weeks last year, and this was the one book that remained consistently in my bag throughout the whole trip. I’m not joking.) In [...]