Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Android Fragments 101
_**Prerequisite**: You are already aware of the [basics of building a HelloWorld](http://developer.android.com/training/index.html) in Android and know [how to use the APIs provided in the support library](http://developer.android.com/training/basics/fragments/support-lib.html)._ _The code example is available on [github](http://github.com/iontech/Fragments_Example "Fragments Example")._ _____________________________________________________________ Ever wanted a code snippet from an Activity to be available to other activities? Perhaps a Button or a ListView, maybe a Layout or any View/ViewGroup for that matter? Fragments let us do just that. Necessity is the mother of invention. Before understanding what Fragments are and how they work, we must first realize their existence in the first place. The Problem ----------- Suppose we have an Android app with two Activities- [*FirstActivity*](https://github.com/iontech/Fragments_Example/blob/master/src/main/java/com/github/iontech/fragments_example/FirstActivity.java) and [*SecondActivity*](https://github.com/iontech/Fragments_Example/blob/master/src/main/java/com/github/iontech/fragments_example/SecondActivity.java). *FirstActivity* contains two Views, a `TextView` (*textView*) and a `Button` (*button1*); and *button1* has an `onClick()` callback that `Toast`'s a simple message "Button pressed". *SecondActivity* contains both the Views present in *FirstActivity* and a `Button` (*button2*). Now we want to utilize the two layout components(Views) of *FirstActivity* in *SecondActivity*, we can go about this with two approaches: 1. Copy and Paste the xml elements of the two Views. 2. Create a separate layout for common Views and reuse it using `` layout element. More about this [here](http://developer.android.com/training/improving-layouts/reusing-layouts.html). Electing the … -
Todo List App: Open Sourced
Announcement: We are open sourcing a few tools we developed recently. Here is the first one. *[Todo List Chrome App](https://github.com/agiliq/to-do-list-chrome-app)* This is a simple todo app - with the key feature that it is completely offline. ### Features 1. Create todo list 2. Create todo 3. Mark as done 4. Delete 5. Totally offline [Get the source](https://github.com/agiliq/to-do-list-chrome-app) or [install the app](https://chrome.google.com/webstore/detail/to-do-list/pmpdkgedikcgfpjbcafckjabeeialdel). -
Password Generator App: Open Sourced
Announcement: We are open sourcing a few tools we developed recently. Here is the second one. [Password Generator Chrome Extension](https://github.com/agiliq/forgot-me-password) [Install it from chrome webstore](https://chrome.google.com/webstore/detail/password-generator/nnjgaeekiplalipomfgacalgehhcckbp) Here are the docs ### Summary A completely client side password generator. ### What is it Its a chrome app to generate unique passwords for each site. Depending upon the domain and a master password a unique password is generated. It doesn't need any server and everything happens on the client side. ### Why? I want to use a unique password for each website. However, I don't want to use lastpass/1password as I find their interface confusing and overkill, and I don't want my password stored on remote servers. I use a simple passwording scheme. I have one master password. For each site, I append the first two letters of the domain to master password and use that as the site password. This is sub-optimal as its easy to understand this scheme, if say two of my passwords are leaked. I want to algorithmically generate the password on the client side, with a chrome app. ### How does it work? password_1 = SHA256(masterpassword+domain) password = take_first_8_letters(password_1) This will generate a per domain password with 8 … -
Tutorial: Building a Chrome app
This is a hands on tutorial about How to build chrome apps, with examples of two Chrome apps we published recently. Lets get started. Chrome apps are of two types: Extensions : They extend the functionality of Google chrome and the websites. They have little or no UI. Ex:Password Generator . Source code : Github Apps: These are separate apps and appear just like any other website. Ex: To Do List. Source Code : Github Depending on our requirement, we need to decide what kind of app we need to build. Extension: Password Generator Installation : Visit the link Password Generator using google-chrome browser and click 'Add To Chrome' button on the top-right corner. Then an extra icon will appear right to the address bar of the browser. If you cant see any icons, try clicking the 'down arrow' that is visible between the address bar and the settings icon. Or just drag and decrease the size of the address bar to see the icons. (see screenshot from the app). Click the icon and a small popup will be opened which is the required app ! What it does : It gets the domain of the currently opened webpage and … -
MoreApps - Android Library Project: Open Sourced
If you have a portfolio of apps, you probably want to cross promote them. We are open sourcing an Android Library Project to make this possible. [Get the code](https://github.com/agiliq/MoreApps). This provides an Activity which you can show with a Grid of your apps. How to use it ------------- Add this MoreAppsLibrary project(library) as a dependency in the Android Application project you are implementing. Add the following code in your `AndroidManifest.xml`: Perform an `Intent` to start the `MoreAppsActivity`; make sure to `putExtra("package", getPackageName());`, this ensures that if the your app is in the list of apps being showcased then your app won't be shown. Intent intent = new Intent(this, MoreAppsActivity.class); intent.putExtra("package", getPackageName()); startActivity(intent); You can refer the **sample** code for a live example. Where does the data come from ----------------------------- The data here is the list of *icons*, the *titles* and the *package names* of the apps. All we do is update the `query` field in `GetAppsDetails` class of the **GetAppsDetails** java app and run this app to get the *icons* and a string resource *xml* file. This xml file contains the titles and package names. *Note: The `query` string would be the same as what you enter in the search … -
Easy client side form validations for Django: Django Parsley
Parsleyjs is a JavaScript library to do client side data validations. It does this in a non-intrusive way via adding a data-* attributes to form fields. Check it out, it's really slick. Django forms do a great job of server side data validations. By integrating Parsley with Django form, you get good client side data validations as well. Get the app here. Some design considerations When I started writing this app I wanted to make it really easy to use. My first thought was to make this a filter or a template tag which would have allowed you to do: {{ form|parsleyfy }} However, I use Django-crispy-forms in all my projects. If parsley was a filter, it would have made piping to |crispy impossible as the render step would already have been completed. Hence parsleyfy is class decorator. Django-crispy-forms and family will play well with parsleyfy. Here is the readme. What is it? Parsleyjs is a JavaScript library to do client side data validations. It does this in a non-intrusive way via adding a data-* attributes to form fields. When you define a Django form, you get server side validations for free using the form field attributes. Django-parsley adds these … -
Introduction to Python Workshop on February 15th, 2013
We are conducting an **"Introduction to Python"** workshop at `our office`_ on **February 15th, 2013 (Friday)** between **5-8PM IST**. This workshop is geared towards those who are planning to learn python. Topics: * Language features * Variables * Built in data structures * Functions * Object Oriented Programming * Demo writing a simple program Prerequisites to attend this session: * A laptop with any linux flavour (OR) a laptop with Python installed in it. Register_ for the workshop by filling up the form. .. _`our office`: http://agiliq.com/contactus#map .. _Register: http://bit.ly/Yf0eiH -
Two Scoops of Django: Review
Two scoops of Django is the new book on Django best practices by Daniel Greenfeld and Audrey Roy. I just finished reading it and found it extremely useful. The book is a collection of tips, their justification and code organized in logical areas. I have been using Django since 2008, but I still found a few tips which were new to me and many which served as good reminder. At about 200 pages, its comprehensive but not overwhelming. If you are an advanced Djangonaut, you can read it in a weekend (And you probably are using all its recommendations anyway). If you are just getting started, putting all the tips to use will keep you busy for month. A random sampling of tips (The book has more than 50 of them.) Use pip, virtualenv and virtualenvwrapper Don't keep your virtualenv inside the project folder Apps should be small and do one thing well Use relative modules, prefer from .models import foo All settings file should be versioned - local_settings.py is an anti-pattern Every settings module should have a corresponding requirements.txt Don't hardcode your paths SingleTable model inheritance is good, multi table model inheritance is bad. Create custom managers, but don't … -
arango: ArangoDB Driver for Python (updated Feb 24, 2013)
Past year I've heard about new database - ArangoDB. I was not able to test it using my daily tools - there was no driver for Python. So, I've decided to create it. I've tried to create really good one - high code coverage, well documented and easy API initially was a must.Yesterday, I've released it - now available on PyPi and on github ToolchainHere is list of basic tools which I've used to create the drivernose - for executing tests, integration and unit. ArangoDB driver contain 103 testscoverage - to have clear metric how many code lines was covered by tests. Now it's 89%sphinx - to have good documentation it's a must. Also .. testcode:: and .. doctest :: directives is very useful to keep code examples usable. PerformanceInitially, I've used requests library as main HTTP transport tool. But at some point I've get a letter from ArangoDB team about python driver performance. Here is most important quote:The guys told me that PHP took 0,5 seconds, JS about a second and our Python script 5 seconds I've start digging and found that requests is slow. Fast tests shows that urllib2 2x faster than requests, and pycurl 3x faster. Here is performance tests … -
Workaround for PostgreSQL SQL_ASCII template encoding
On some Linux distribution installs there may be a problem with SQL_ASCII encoding set on postgres templates (I found it on the daily ISO Raring Ringtail install). When trying to create postgis template with UTF-8 encoding it will fail with an error: createdb: database creation failed: ERROR: new encoding (UTF8) is incompatible with the encoding of the template database (SQL_ASCII) In Django documentation there is a link to one of workarounds - recreating the whole cluster, which results in dropping all databases. There is however an less aggressive fix for this problem - drop template1 and recreate it from template0 using UTF-8 encoding and dropping template_postgis if it exists with the wrong encoding. When template1 is recreated the "create_template_postgis*.sh" script can be used. To drop and create "template1" use the tutorial at journal.tianhao.info. If "template_postgis" exists drop it basing on the step 1 and 2 from the tutorial. After that you can create the postgis template with the Django bash script file (or manually using for example archlinux tutorial). -
New plugins to the Kate, utils to: Python, JavaScript, Django and XML
The project plugin in kate.git master now has four new more plugins, with many features in each one: Python (autocomplete, smart snippets, parse checker, pep8 checker and pyflakes checker), Javascript (autocompletes, jquery snippet, pretty JSON, and jslint checker), Django (smart snippets and utils to Django template) and XML (pretty xml). There are also many generic functions and generic classes in these that will be useful to the new plugins developers. I began to develop these plugins in 2009, this was my first version :-). I wanted to set a shortcut to a snippet, as it was not possible (now it is posible) I started to develop these plugins to Kate. In November 2011, I created a repository on github to develop new features and share them. I have to thank Alejandro Blanco, Jeroen van Veen, Javier Romero, Martin Borho, Justin Chudgar and Yaco Sistemas for helping me in this project. In October 2012 Christoph Cullmann (Kate maintainer) sent me an e-mail, in which he asked me if I was interested to contribute with KDE project. I answered: “Of course!”…. finally I have a little time, and I have been able to integrate these plugins in the kate.git Features to Python … -
Functions in Python presentation
Here is my presentation part of the in company Python course. Functions in python from Ilian Iliev The last slide – “Problem to solve” is something like a simple homework. Sample solutions will be uploaded later this week. -
Values instance has no attribute 'default_reference_context'
I was just editing some reStructuredText content for my website when Django threw a strange error at me. Values instance has no attribute 'default_reference_context' What was really bizarre is that exactly the same rst content could be published as HTML just fine in a test script: from docutils.core import publish_parts rst = 'real content here' print publish_parts(rst, writer_name='html')['html_body'] I couldn't find anything relevant anywhere on the internet either. After some trial and error I managed to find the source of the problem: `hyperlink <http://example.com>` Did you spot the error? The trailing underscore is missing, a valid link would look like: `hyperlink <http://example.com>`_ I still have no idea why the same code would raise an exception inside Django but work stand-alone (but of course generate unwanted markup). Anyway, problem solved for me. Updates: other sources for the error `foo` Renders as <cite> outside of Django. Solved The problem has existed for five years in Django core, see #6681. A simple solution is to disable the admindocs app. Yes, the app messes with the docutils settings project-wide. -
Values instance has no attribute 'default_reference_context'
I was just editing some reStructuredText content for my website when Django threw a strange error at me. Values instance has no attribute 'default_reference_context' What was really bizarre is that exactly the same rst content could be published as HTML just fine in a test script: from docutils.core import publish_parts rst = 'real content here' print publish_parts(rst, writer_name='html')['html_body'] I couldn't find anything relevant anywhere on the internet either. After some trial and error I managed to find the source of the problem: `hyperlink <http://example.com>` Did you spot the error? The trailing underscore is missing, a valid link would look like: `hyperlink <http://example.com>`_ I still have no idea why the same code would raise an exception inside Django but work stand-alone (but of course generate unwanted markup). Anyway, problem solved for me. Updates: other sources for the error `foo` Renders as <cite> outside of Django. Solved The problem has existed for five years in Django core, see #6681. A simple solution is to disable the admindocs app. Yes, the app messes with the docutils settings project-wide. -
Migrating to Heroku
To cut some personal costs and simply because I was interested in it, I recently moved this blog to Heroku, the popular cloud hosting platform. Since 2011 Heroku officially supports Python deployments. Running on a single dyno it is even for free. Following the official guide to deploy a Django application, the transition from my VPS to Heroku was pretty straight-forward and easy. Additionally Heroku enforces good practices, like using virtualenv, and supports more and more popular technologies, like the Python WSGI server Gunicorn. Following a short general guide of what had to be done from my side to do the transition: Create a fixture file from your database via the dumpdata command. Since I didn't want to add any billing information to Heroku yet, I had to rewrite everything related to sending emails from my web server, to save the incoming contact request in the database instead. That was pretty much just the creation of a new model and a one-liner to save it to the DB instead of sending an email, Already using virtualenv, the rest was simply adding or changing requirements. In addition of removing the MySQL bindings for python I added the following libaries: dj-database-url==0.2.1 django-heroku-memcacheify==0.4 … -
At last - fixed RSS feeds
It's been more than two years that this site has been running on Django, but I had never gotten around to making really good RSS feeds. Some entries didn't contain the relevant content, others didn't format it properly, etc. Fortunately I have learned enough about Django by now that it only took me a few minutes to fix this.. at last. In case you're wondering, I simply use render_to_string and re-use the already existing template snippets in the item_description methods of the feed classes. It's so obvious, I'm not sure why I didn't think of it when I built this site, which was my first Django project. -
At last - fixed RSS feeds
It's been more than two years that this site has been running on Django, but I had never gotten around to making really good RSS feeds. Some entries didn't contain the relevant content, others didn't format it properly, etc. Fortunately I have learned enough about Django by now that it only took me a few minutes to fix this.. at last. In case you're wondering, I simply use render_to_string and re-use the already existing template snippets in the item_description methods of the feed classes. It's so obvious, I'm not sure why I didn't think of it when I built this site, which was my first Django project. -
Django Settings Parity: You're Doing It Wrong
Click here to see this post in it's natural habitat and to watch and leave comments. A common paradigm in Django is to create different settings files for different environments (local, production, staging, etc.). Everyone has their own opinion on how to set these up (see ours here), that’s not what this post is about. Instead, I’d like to point out the inherent danger in this technique and how to prevent shooting yourself in the foot. When setting up an environment-specific settings file, each setting should be looked at as an untestable point-of-failure. Have you ever found yourself saying, “...but it worked fine on {staging, my machine, etc.}”? This is a problem of parity and it starts with your settings files. Just because you can change all your settings between environments, it doesn’t mean you should. Use restraint. Make your settings as close as possible between environments and examine every divergence to make sure it is absolutely necessary (inheriting from a common base settings file makes the comparison easy). Here’s a few things that you’ll likely need to change between your environments: database connection details SECRET_KEY 3rd party API keys If your settings switches only contain those types values, then … -
Django Settings Parity: You're Doing It Wrong
A common paradigm in Django is to create different settings files for different environments (local, production, staging, etc.). Everyone has their own opinion on how to set these up (see ours here), that’s not what this post is about. Instead, I’d like to point out the inherent danger in this technique and how to prevent shooting yourself in the foot. When setting up an environment-specific settings file, each setting should be looked at as an untestable point-of-failure. Have you ever found yourself saying, “...but it worked fine on {staging, my machine, etc.}”? This is a problem of parity and it starts with your settings files. Just because you can change all your settings between environments, it doesn’t mean you should. Use restraint. Make your settings as close as possible between environments and examine every divergence to make sure it is absolutely necessary (inheriting from a common base settings file makes the comparison easy). Here’s a few things that you’ll likely need to change between your environments: database connection details SECRET_KEY 3rd party API keys If your settings switches only contain those types values, then pat yourself on the back. If, on the other hand, they vary on things like: installed … -
Django Settings Parity: You're Doing It Wrong
A common paradigm in Django is to create different settings files for different environments (local, production, staging, etc.). Everyone has their own opinion on how to set these up (see ours here), that’s not what this post is about. Instead, I’d like to point out the inherent danger in this technique and how to prevent shooting yourself in the foot. -
Batch image upload with drag and drop in the Django admin
The assignment: Find a way to implement batch image uploads in the Django admin using a drag and drop interface. For the record, we're using jQuery 1.8, and Bootstrap for some of the styling. Temporary files are being posted to S3, using boto (for more information: http://boto.s3.amazonaws.com/s3_tut.html), while the final uploads on form save are going to MEDIA_ROOT/{upload_to value}. Luckily, I started with a pretty simple model - for each image, there's an upload field that stores the path, and some metadata around that (we use PIL to determine height and width, and sorl for thumbnails, but I'm not going to cover either of those here): # models.py class Image(Content): """ Simple model for image file metadata """ image = models.ImageField(upload_to='images/') width = models.IntegerField() height = models.IntegerField() credit = models.CharField(max_length=255, blank=True) display_caption = models.BooleanField(default=True) pub_date = models.DateTimeField((u'Publication Date')) The form is fairly basic as well - note that while I'm listing the handful of metadata fields that I want to capture, I am not including the 'image' field itself: #forms.py class MultiImageUploadForm(ModelForm): """ This form is only used to handle the uploads """ class Meta: fields = ('credit', 'display_caption', 'pub_date',) model = Image def __init__(self, *args, **kwargs): super(MultiImageUploadForm, self).__init__(*args, **kwargs) … -
2.3.5 Security release
-
django CMS 2.3.4 released
-
Buildout 2.0 is out! What to do in case of an error.
zc.buildout 2.0.0 is out, hurray! Quite some nice things in there which I'll write down in another post. Something breaks? I saw some bug reports on a mailinglist and on stack overflow (example 1, example 2) about buildouts suddenly breaking since buildout 2.0 is out. Most extensions and buildout recipes work just fine with the latest buildout, but some break due to some internal buildout classes and imports being changed or moved around. Solution: take a newer bootstrap Buildout 1.5/1.6/1.7 really changed something compared to buildout 1.4. More isolation from the system python was added, but this didn't work everywhere. There was a special bootstrap that kept you on buildout 1.4.4. If you used that one, you can probably switch to buildout 2.0. Take the 2.0 bootstrap: http://downloads.buildout.org/2/bootstrap.py If you want to stay on 1.5/1.6/1.7, you really want to stick to 1.7. That includes a build-in version restriction for zc.buildout to be less than 2.0. The 1.x bootstrap will keep you in 1.x land: http://downloads.buildout.org/1/bootstrap.py For most "help" questions, the quickest answer has been to pick this bootstrap and run it and by happy. Upgrading? Real quick instructions. Well, use the 2.0 bootstrap: http://downloads.buildout.org/2/bootstrap.py If somewhere you've pinned buildout and … -
Django almost spaceless template tag
Django has a {{ spaceless }} tag that's a little too greedy for my taste. Removing all whitespace between HTML tags can actually change what the browser renders, so here's a less greedy variant. However, it removes all whitespace, not just between tags, so if you use the pre tag for example you don't want this. class AlmostSpacelessNode(Node): def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): return self.remove_whitespace(self.nodelist.render(context).strip()) def remove_whitespace(self, value): value = re.sub(r'\n', ' ', value) value = re.sub(r'\s+', ' ', value) return value @register.tag(name='almostspaceless') def spaceless(parser, token): """ Remove all whitespace except for one space from content """ nodelist = parser.parse(('endalmostspaceless',)) parser.delete_first_token() return AlmostSpacelessNode(nodelist)