Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Template fragment caching gotchas
Variables in cached template fragment Assuming this is in template. {% cache 300 nums %} {% for i in nums %} <p>i</p> {% endfor %} {% endcache %} And assuming we send {'nums': range(100)} from context, then 0 to 99 will be sent in the response. Now suppose we change context to {'nums': range(1000)}, still for next 5 minutes i.e until the cache expires, 0 to 99 will be sent in the response. 0 to 999 will not be sent in the response. To fix this, we should use the variable too with the {% cache %} tag. So correct code would be {% cache 300 nums_cache nums %} {% for i in nums %} <p>i</p> {% endfor %} {% endcache %} After this whenever context nums changes, cache would be reevaluated. Boolean variable in cached template fragment Assuming template contains {% cache 300 hello %} {% if hello %} <p>Hello</p> {% endif %} {% endcache %} and assuming {'hello': True} is sent in context. Then <p>Hello</p> will be sent in response. Now even when we send {'hello': False} in context, "<p>Hello</p>" will still be sent in response because it's already cached. To fix this. {% cache 300 hello_cache hello … -
Announcing Django Girls RDU: Free Coding Workshop for Women
We’re incredibly excited to announce the launch of Django Girls RDU, a group in NC’s Triangle region that hosts free one-day Django coding workshops for women. Django Girls is part of an international movement that’s helped 1,600 (and counting!) women learn how to code. We originally got involved with Django Girls at the impetus of our Technical Director, Mark Lavin. While discussing our efforts to support women in tech, Mark was emphatic: there was this group, Django Girls, that was doing extraordinary work engaging women in Django. Clearly, we needed something like that locally. Luckily for us, Django Girls was coming to PyCon and we'd get to see first hand just how wonderful they are. Four of our team members volunteered as coaches for a Django Girls workshop during PyCon 2015. There was nothing quite like seeing the impact Django Girls had on each attendee. The environment was warm, friendly, and infectiously enthusiastic. The tutorials for students, coaches, and organizers, were very thoughtful and detailed. The passion of the Django Girls organizers was evident in every moment. Out of a desire to prolong this excitement and share it with everyone we knew, we put together a team and applied to … -
[Django Tips] Use for ... empty in Django templates.
It is quite common to send a query set from a view to template, loop over it and display items in it. If no items are there, it is good if we display some message. For that we can do something like this.{% if books %} {% for book in books %} <li>{{ book }}</li> {% endfor %}{% else %} <li>Sorry, there are no books.</li>{% endif %}Django {% for %} tag takes an optional {% empty %} clause which will be rendered when queryset is empty. So we can rewrite the above code as{% for book in books %} <li>{{ book }}</li>{% empty %} <li>Sorry, there are no books.</li>{% endfor %}This code is much cleaner than previous one. I tried to profile both code blocks. The first block took 0.9ms and second block took 0.8ms which means it is 11% faster than previous code :)Reference: Django docsRead more articles about Python!Read more articles about Django! -
Django Tips & Tricks #5 - Use for...empty in Django templates
It is quite common to send a query set from a view to template, loop over it and display items in it. If no items are there, it is good if we display some message. For that we can do something like this.{% if books %} {% for book in books %} <li>{{ book }}</li> {% endfor %}{% else %} <li>Sorry, there are no books.</li>{% endif %}Django {% for %} tag takes an optional {% empty %} clause which will be rendered when queryset is empty. So we can rewrite the above code as{% for book in books %} <li>{{ book }}</li>{% empty %} <li>Sorry, there are no books.</li>{% endfor %}This code is much cleaner than previous one. I tried to profile both code blocks. The first block took 0.9ms and second block took 0.8ms which means it is 11% faster than previous code :)Reference: Django docs -
Understanding 'GenericForeignKey' in Django
In some cases the we might want to store generic model object, rather a particular specific model as 'ForeignKey'. Here is scenario of such kind. Suppose there are models like User, Project, Ticket and TimeLine as below. class Ticket(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class Project(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class User(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class Timeline(models.Model): involved_object = ***** event_type = models.CharField(max_length=250, default="created") If we want to store the user activities with these models like "created User, created Project, created Task" in time line, we have to create all the three models(User, Project, Task) as 'ForeignKey' fields. This is not a good programming practice. To overcome this, Django's contenttypes framework provides a special field type (GenericForeignKey) which allows the relationship to be with any model. Using 'GenericForeignKey' : Here is the solution for the above scenario. There are three parts to setting up a GenericForeignKey: Give your model a ForeignKey to ContentType. The usual name for this field is “content_type”. Give your model a field that can store primary key values from the models you’ll be relating to. For … -
Understanding 'GenericForeignKey' in Django
In some cases we might want to store generic model object, rather a particular specific model as 'ForeignKey'. Here is the scenario of such kind. Suppose there are models like User, Project, Ticket and TimeLine as below. class Ticket(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class Project(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class User(models.Model): name = models.CharField(max_length=200, verbose_name=_("name")) slug = models.SlugField(max_length=250, null=False, blank=True, verbose_name=_("slug")) class Timeline(models.Model): involved_object = ***** event_type = models.CharField(max_length=250, default="created") If we want to store the user activities with these models like "created User, created Project, created Task" in a timeline, we have to create all the three models(User, Project, Task) as 'ForeignKey' fields. This is not a good programming practice. To overcome this, Django's content types framework provides a special field type (GenericForeignKey) which allows the relationship to be with any model. Using 'GenericForeignKey': Here is the solution for the above scenario. There are three parts to setting up a GenericForeignKey: Give your model a ForeignKey to ContentType. The usual name for this field is “content_type”. Give your model a field that can store primary key values from the models you’ll be relating to. For … -
Using Unsaved Related Models for Sample Data in Django 1.8
Note: In between the time I originally wrote this post and it getting published, a ticket and pull request were opened in Django to remove allow_unsaved_instance_assignment and move validation to the model save() method, which makes much more sense anyways. There's a chance this will even be backported to Django 1.8. So, if you're using a version of Django that doesn't require this, hopefully you'll never stumble across this post in the first place! If this is still an issue for you, here's the original post: In versions of Django prior to 1.8, it was easy to construct "sample" model data by putting together a collection of related model objects, even if none of those objects was saved to the database. Django 1.8 adds a restriction that prevents this behavior. Errors such as this are generally a sign that you're encountering this issue: ValueError: Cannot assign "...": "MyRelatedModel" instance isn't saved in the database. The justification for this is that, previously, unsaved foreign keys were silently lost previously if they were not saved to the database. Django 1.8 does provide a backwards compatibility flag to allow working around the issue. The workaround, per the Django documentation, is to create a … -
PyCon 2015 Workshop Video: Building SMS Applications with Django
As proud sponsors of PyCon, we hosted a one and a half hour free workshop. We see the workshops as a wonderful opportunity to share some practical, hands-on experience in our area of expertise: building applications in Django. In addition, it’s a way to give back to the open source community. This year, Technical Director Mark Lavin and Developers Caleb Smith and David Ray presented “Building SMS Applications with Django.” In the workshop, they taught the basics of SMS application development using Django and Django-based RapidSMS. Aside from covering the basic anatomy of an SMS-based application, as well as building SMS workflows and testing SMS applications, Mark, David, and Caleb were able to bring their practical experience with Caktus client projects to the table. We’ve used SMS on behalf of international aid organizations and agencies like UNICEF as a cost-effective and pervasive method for conveying urgent information. We’ve built tools to help Libyans register to vote via SMS, deliver critical infant HIV/AIDs results in Zambia and Malawi, and alert humanitarian workers of danger in and around Syria. Interested in SMS applications and Django? Don’t worry. If you missed the original workshop, we have good news: we recorded it. You can … -
Reviews of two recent Django Books
Introduction When I started building sites in Django, I learned the basics from the excellent Django tutorial. But I had to learn by trial and error which approaches to using Django's building blocks worked well and which approaches tended to cause problems later on. I looked for more intermediate-level documentation, but beyond James Bennett's Practical Django Projects and our Karen Tracey's Django 1.1 Testing and Debugging, there wasn't much to be found. Over the years, ever more interesting introductory material has been showing up, including recently our lead technical manager Mark Lavin's Lightweight Django. But more experienced developers are also in luck. Some of the community's most experienced Django developers have recently taken the time to put down their experience in books so that we can all benefit. I've been reading two of those books and I can highly recommend both. Two Scoops of Django I guess Two Scoops of Django, by Daniel Roy Greenfeld and Audrey Roy Greenfeld, isn't that recent; its third edition just came out. It's been updated twice to keep up with changes in Django (the latest edition covers Django 1.8), improve the existing material, and add more information. The subtitle of the most recent edition … -
Django and Python 3 How to Setup pyenv for Multiple Pythons
We need to be doing Django development in Python 3. Unfortunately, we have a lot of projects still in Python 2.7 so switching between the 2 versions can be frustrating. Fortunately pyenv takes the guess work out of switching, and makes it super simple.Watch Now... -
A couple quick tips
As noted yesterday, I’ve spent the last little while working to freshen up various bits of open-source code I maintain, in order to make sure all of them have at least one recent release. Along the way I’ve picked up a few little tips and tricks; some of them may be old hat to you if you’ve been lucky enough to be working with fairly modern Django and Python versions for a while, but I ... Read full entry -
A couple quick tips
As noted the other day, I’ve spent the last little while working to freshen up various bits of open-source code I maintain, in order to make sure all of them have at least one recent release. Along the way I’ve picked up a few little tips and tricks; some of them may be old hat to you if you’ve been lucky enough to be working with fairly modern Django and Python versions for a while ... Read full entry -
Testing Django Views Without Using the Test Client
Testing Django Views Without Using the Test Client -
[Django Tips] Make Django Development Server Persistent.
I use Emacs for writing Python code. I also use real-auto-save to save my files after 10 seconds of inactivity.While coding, when I stop writing in the middle, after 10 seconds Emacs auto saves the file. Django recognizes this & reloads the development server.Once I complete writing code, I go to browser & refresh the page. Since the code I was writing was incomplete somewhere in the middle and had some errors, Django development server was stopped and page won't reload. Now I have to go back to terminal and restart the server and again go back to browser to refresh page.To overcome this, Django server must be made persistent. The easiest way to accomplish this is to use a simple bash script as described here.$ while true; do python manage.py runserver; sleep 4; doneWhen Django development server stops, after 4 seconds it tries to start automatically and goes on forever.Instead of typing that everytime, it better to write this as a shell script and put it in system path, so that it can be used in any project.while true; do echo "Re-starting Django runserver" python manage.py runserver sleep 4doneSave this & make it executable(chmod +x), use it is ./filename.sh and to stop … -
The uWSGI Swiss Army Knife
uWSGI is one of those interesting projects that keeps adding features with every new release without becoming totally bloated, slow, and/or unstable. In this post, we'll look at some of its lesser used features and how you might use them to simplify your Python web service. Let's start by looking at a common Python web project's deployment stack. Nginx: Static file serving, SSL termination, reverse proxy Memcached: Caching Celery: Background task runner Redis or RabbitMQ: Queue for Celery uWSGI: Python WSGI server Five services. That's a lot of machinery to run for a basic site. Let's see how uWSGI can help you simplify things: Static File Serving uWSGI can serve static files quite efficiently. It can even do so without tying up the same worker/thread pool your application uses thanks to it's offloading subsystem. There are a bunch of configuration options around static files, but the common ones we use are: offload-threads the number of threads to dedicate to serving static files check-static this works like Nginx's @tryfiles directive, checking for the existence of a static file before hitting the Python application static-map does the same, but only when a URL pattern is matched Other options exist to allow you … -
Django Tips & Tricks #4 - Make Django Development Server Persistent
I use Emacs for writing Python code. I also use real-auto-save to save my files after 10 seconds of inactivity.While coding, when I stop writing in the middle, after 10 seconds Emacs auto saves the file. Django recognizes this & reloads the development server.Once I complete writing code, I go to browser & refresh the page. Since the code I was writing was incomplete somewhere in the middle and had some errors, Django development server was stopped and page won't reload. Now I have to go back to terminal and restart the server and again go back to browser to refresh page.To overcome this, Django server must be made persistent. The easiest way to accomplish this is to use a simple bash script as described here.$ while true; do python manage.py runserver; sleep 4; doneWhen Django development server stops, after 4 seconds it tries to start automatically and goes on forever.Instead of typing that everytime, it better to write this as a shell script and put it in system path, so that it can be used in any project.while true; do echo "Re-starting Django runserver" python manage.py runserver sleep 4doneSave this & make it executable(chmod +x), use it is ./filename.sh … -
News and such
First things first: though I announced this sort of quietly at the time, I should probably announce it publicly as well: after four years as part of the MDN development team, as of last month I am no longer at Mozilla. There are some parallels to the last time I moved on, so I’ll link to that in lieu of writing it all over again. For the moment I’m enjoying a summer vacation, but I’m ... Read full entry -
News and such
First things first: though I announced this sort of quietly at the time, I should probably announce it publicly as well: after four years as part of the MDN development team, my final day at Mozilla was early last month. There are some parallels to the last time I moved on, so I’ll link to that in lieu of writing it all over again. For the moment I’m enjoying a summer vacation, but I’m at ... Read full entry -
Understanding Django Middlewares
I assume you have read official Django docs on middleware. I will elaborate on things mentioned in the documentation but I assume you are familiar with basics of middleware. In this post we will discuss the following. What is a middleware When to use middleware Things to remember when writing middleware Writing some middlewares to understand how order of middleware matters What is a middleware Middlewares are hooks to modify Django request or response object. Putting the definition of middleware from Django docs. Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output. When to use middleware You can use middleware if you want to modify the request i.e HttpRequest object which is sent to the view. Or you might want to modify the HttpResponse object returned from the view. Both these can be achieved by using a middleware. You might want to perform an operation before the view executes. In such case you would use a middleware. Django provides some default middleware. eg: AuthenticationMiddleware Very often you would have used request.user inside the view. Django wants user attribute to be set on request before any view … -
Profiling Django Middlewares
I assume you have a basic understanding of Profiling, what it means and why we use it. Why this post Recently I had to profile a Django application which wasn't performing as fast as it should. This application had several custom middlewares too. So it was possible that custom middlewares were the cause of slow performance. There are some existing Django libraries to profile Django code. eg: Django Debug Toolbar, django-silk , django_cprofile etc. Most of them can profile view code well but they can't profile other middlewares. I wanted a way to profile middlewares too. Problem with Django Debug Toolbar I assume you understand middlewares and how the order in which middlewares are defined matter. If you want to get more idea about middlewares, this post might help. Django debug toolbar is probably designed for profiling the views. It uses process_view() and returns an HttpResponse instace from process_view(). process_request() of all middlewares run before any middleware's process_view(). So using Django debug toolbar, it's not possible to profile what's going on inside process_request() of different middlewares. And since process_view() of debug toolbar returns HttpResponse, process_view() of other middlewares is bypassed and so we can't profile process_view() of other middlewares. So … -
How to access your Django site from a different computer
Hey guys! Today we'll see how to access your Django site from another computer. Now this won't be a problem if you've hosted on a remote server like PythonAnywhere or Heroku. But what if you have hosted it on your local machine and want to provide people with access to it?I'm developing an online mentorship platform for my college that is hosted on the college server. So for that I had to use this concept. Before you do this, however, here's a disclaimer: only computers connected in the same network as your local machine can access your Django site. You can, of course, provide global access, but there's a lot of complicated networking stuff involved in that. Let's not go into that right now.So let's get on with it. You know the command for hosting and accessing the site on your local machine is python manage.py runserver. This essentially gives your local machine server capabilities and lets you access it from the same machine. However, to let other machines access it, here's the command:python manage.py runserver <ip_address>:<port_number>Replace <ip_address> with your machine's IP address. If you don't know the IP address, do one of the following:Windows: Open command prompt and type ipconfig. … -
Django Birthday: Recap
Django Birthday: Recap -
Q3 2015 ShipIt Day ReCap
Last Friday marked another ShipIt Day at Caktus, a chance for our employees to set aside client work for experimentation and personal development. It’s always a wonderful chance for our developers to test new boundaries, learn new skills and sometimes even build something entirely new in a single day. NC Nwoko and Mark Lavin teamed up to develop a pizza calculator app. The app simply and efficiently calculates how much pizza any host or catering planner needs to order to feed a large group of people. We eat a lot of pizza at Caktus. Noticing deficiencies in other calculators on the internet, NC and Mark built something simple, clean, and (above all) well researched. In the future, they hope to add size mixing capabilities and as well as a function for calculating the necessary ratios to provide for certain dietary restrictions, such as vegan, vegetarian, or gluten-free eaters. Jeff Bradberry and Scott Morningstar worked on getting Ansible functioning to replace SALT states in the Django project template and made a lot of progress. And Karen Tracey approached some recent test failures, importing solutions from the database, while Rebecca Muraya began the massive task of updating some of our client based … -
Repository for existing Extbase model class
If you want to use an existing extbase model like Category but want to create a custom repository to implement some custom queries, here is the way to go: Create typo3conf/ext/your_ext/Classes/Domain/Model/Category.php: <?php namespace Dummy\YourExt\Domain\Model; /** * Category */ class Category extends \TYPO3\CMS\Extbase\Domain\Model\Category { } Create typo3conf/ext/your_ext/Classes/Domain/Repository/CategoryRepository.php: <?php namespace Dummy\YourExt\Domain\Repository; /** * The repository for Categories */ class CategoryRepository extends \TYPO3\CMS\Extbase\Domain\Repository\CategoryRepository { // some custom query methods here } Create typo3conf/ext/your_ext/ext_typoscript_setup.txt: config.tx_extbase{ persistence{ classes{ Dummy\YourExt\Domain\Model\Category { mapping { tableName = sys_category recordType = Tx_YourExt_Category } } } } } Clear the cache and you're ready to go! -
Frontend Code Strategy with Django
Web development is getting more and more focused on front-end development. This leads to a lot of questions on what is the best way to handle compiling css, javascript, coffeescirpt, stylus, etc. Having been involved with a project where the frontend deals with 100+ files between stylus files, coffeescirpt files, javascript, and css. This is kind of crazy to manage without a good strategy or even knowing how to accomplish it. How Frontend Code Works in Django When working with django you need to consider how the code is going to go from your code base to be displayed in the browser. The normal path it takes is to live in a static directory which you edit and run locally. Then in production you do a collectstatic command and it moves everything to a folder for your webserver to pull from. With that in mind as long as the above happens you can do almost anything you want for your frontend code. Lets take a look at the 3 most common ways you can do front-end development with django. Three Popular Ways to Write Frontend Code Everything in the static folder The most common way we start projects is to …