Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
CSV Files - Read and Create
CSV files seem to be what some companies live by. Because of that we need to know how to work with them. In this video learn the basics of using csv reader, writer, DictReader, and DictWriterWatch Now... -
Special Offer for the Readers of DjangoTricks Blog
Packt Publishing, the company that published my Django book, has a special offer for enthusiast and professional developers reading this blog. For two weeks you can get the eBook "Web Development with Django Cookbook - Second Edition" for half price. The eBook is available in PDF, ePub, Mobi, and Kindle formats. Also you will get access to download the related code files. Use the discount code DJGTRK50 at the Packt Publishing bookstore.The discount is valid until the 24th of February, 2016. -
Just one comma
In Django, if you say managed = False in a model's Meta, you tell Django not to touch the database table. So: no automatic database migrations, for instance. Now, what is the problem if you have managed = False, and Django does do migrations? Some of you will have seen the error already. The comma after False is the problem: >>> a = False, >>> a (False,) >>> bool(a) True The comma turns it into a tuple. And a non-empty tuple evaluates to True! I found it quite funny. My colleague was torn between "extremely relieved" and "extremely annoyed" :-) -
Wagtail and Streamfields
Django was always great for developers out of the box, but creating friendly admin interfaces was always a little too much work. This post explains why I now consider using Wagtail to make this task easier. -
Wagtail and Streamfields
Django was always great for developers out of the box, but creating friendly admin interfaces was always a little too much work. This post explains why I now consider using Wagtail to make this task easier. -
Wagtail and Streamfields
Django was always great for developers out of the box, but creating friendly admin interfaces was always a little too much work. This post explains why I now consider using Wagtail to make this task easier. -
Fresh Book for Developers Working with Django 1.8
This week the post office delivered a package that made me very satisfied. It was a box with three paper versions of my "Web Development with Django Cookbook - Second Edition". The book was published at the end of January after months of hard, but fulfilling work in the late evenings and on weekends. The first Django Cookbook was dealing with Django 1.6. Unfortunately, the support for that version is over. So it made sense to write an update for a newer Django version. The second edition was adapted for Django 1.8 which has a long-term support until April 2018 or later. This edition introduces new features added to Django 1.7 and Django 1.8, such as database migrations, QuerySet expressions, or System Check Framework. Most concepts in this new book should also be working with Django 1.9. My top 5 favourite new recipes are these: Configuring settings for development, testing, staging, and production environments Using database query expressions Implementing a multilingual search with Haystack Testing pages with Selenium Releasing a reusable Django app The book is worth reading for any Django developer, but will be best understood by those who already know the basics of web development with Django. You … -
Django Haystack and Elasticsearch- part one
Hello! Today blog post is about Django Haystack and how to integrate it quickly with Elasticsearch. First after creating django project (At beginning of 2016 django-haystack don't work properly with django 1.9 so I used 1.8.9 version) and making new app let's add models: from django.db import models GENDER_CHOICES = ( ('Male', 'Male'), ('Female', 'Female') ) class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) email = models.CharField(max_length=100) ip_address = models.CharField(max_length=100) def __str__(self): return '{first_name} {last_name}'.format(first_name=self.first_name, last_name=self.last_name) And register model to the admin site. Don't forget about adding created app to settings.py and making manage.py makemigrations and manage.py migrate after it: from django.contrib import admin from .models import Person admin.site.register(Person) Then create simple script wich will load a data from JSON to the database. This JSON data is randomly generated data from this webpage. Call it load.py and place in your django application folder. # coding=utf-8 import os import json from .models import Person DATA_FILE = os.path.join( os.path.dirname( os.path.dirname( os.path.dirname(__file__))), 'MOCK_DATA.json' ) def run(verbose=True): with open(DATA_FILE) as data_file: data = json.load(data_file) for record in data: Person.objects.create( first_name=record['first_name'], last_name=record['last_name'], gender=record['gender'], email=record['email'], ip_address=record['ip_address']) print(record) This script looks for file MOCK_DATA.json. Then based on fields on this JSON loads data … -
Django Haystack and Elasticsearch- part one
Hello! Today blog post is about Django Haystack and how to integrate it quickly with Elasticsearch. First after creating django project (At beginning of 2016 django-haystack don't work properly with django 1.9 so I used 1.8.9 version) and making new app let's add models: from django.db import models GENDER_CHOICES = ( ('Male', 'Male'), ('Female', 'Female') ) class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) email = models.CharField(max_length=100) ip_address = models.CharField(max_length=100) def __str__(self): return '{first_name} {last_name}'.format(first_name=self.first_name, last_name=self.last_name) And register model to the admin site. Don't forget about adding created app to settings.py and making manage.py makemigrations and manage.py migrate after it: from django.contrib import admin from .models import Person admin.site.register(Person) Then create simple script wich will load a data from JSON to the database. This JSON data is randomly generated data from this webpage. Call it load.py and place in your django application folder. # coding=utf-8 import os import json from .models import Person DATA_FILE = os.path.join( os.path.dirname( os.path.dirname( os.path.dirname(__file__))), 'MOCK_DATA.json' ) def run(verbose=True): with open(DATA_FILE) as data_file: data = json.load(data_file) for record in data: Person.objects.create( first_name=record['first_name'], last_name=record['last_name'], gender=record['gender'], email=record['email'], ip_address=record['ip_address']) print(record) This script looks for file MOCK_DATA.json. Then based on fields on this JSON loads data … -
Django Haystack and Elasticsearch- part one
First part of tutorial about django haystack with elasticsearch. -
How to no-mincss links with django-pipeline
This might be the kind of problem only I have, but I thought I'd share in case others are in a similar pickle. Warming Up First of all, the way my personal site works is that every rendered page gets cached as rendered HTML. Midway, storing the rendered page in the cache, an optimization transformation happens. It basically takes HTML like this: <html> <link rel="stylesheet" href="vendor.css"> <link rel="stylesheet" href="stuff.css"> <body>...</body> </html> into this: <html> <style> /* optimized contents of vendor.css and stuff.css minified */ </style> <body>...</body> </html> Just right-click and "View Page Source" and you'll see. When it does this it also filters out CSS selectors in those .css files that aren't actually used in the rendered HTML. This makes the inlined CSS much smaller. Especially since so much of the CSS comes from a CSS framework. However, there are certain .css files that have references to selectors that aren't in the generated HTML but are needed later when some JavaScript changes the DOM based on AJAX or user actions. For example, the CSS used by the Autocompeter widget. The program that does this CSS optimization transformation is called mincss and it has a feature where you can tell it … -
How to no-mincss links with django-pipeline
This might be the kind of problem only I have, but I thought I'd share in case others are in a similar pickle. Warming Up First of all, the way my personal site works is that every rendered page gets cached as rendered HTML. Midway, storing the rendered page in the cache, an optimization transformation happens. It basically takes HTML like this: <html> <link rel="stylesheet" href="vendor.css"> <link rel="stylesheet" href="stuff.css"> <body>...</body> </html> into this: <html> <style> /* optimized contents of vendor.css and stuff.css minified */ </style> <body>...</body> </html> Just right-click and "View Page Source" and you'll see. When it does this it also filters out CSS selectors in those .css files that aren't actually used in the rendered HTML. This makes the inlined CSS much smaller. Especially since so much of the CSS comes from a CSS framework. However, there are certain .css files that have references to selectors that aren't in the generated HTML but are needed later when some JavaScript changes the DOM based on AJAX or user actions. For example, the CSS used by the Autocompeter widget. The program that does this CSS optimization transformation is called mincss and it has a feature where you can tell it … -
Writing Unit Tests for Django Migrations
Testing in a Django project ensures the latest version of a project is as bug-free as possible. But when deploying, you’re dealing with multiple versions of the project through the migrations. The test runner is extremely helpful in its creation and cleanup of a test database for our test suite. In this temporary test database, all of the project's migrations are run before our tests. This means our tests are running the latest version of the schema and are unable to verify the behavior of those very migrations because the tests cannot set up data before the migrations run or assert conditions about them. We can teach our tests to run against those migrations with just a bit of work. This is especially helpful for migrations that are going to include significant alterations to existing data. The Django test runner begins each run by creating a new database and running all migrations in it. This ensures that every test is running against the current schema the project expects, but we'll need to work around this setup in order to test those migrations. To accomplish this, we'll need to have the test runner step back in the migration chain just for … -
Django Trees via Closure View
After writing up a method of using a Postgres View that generates a materialised path within the context of a Django model, I came across some queries of my data that were getting rather troublesome to write. It occurred to me that having a closure table would be useful. Specifically, I needed all of the descendants of a given set of nodes. I couldn't find an existing Postgres extension that will manage the closure table, and didn't feel like writing my own implemention using triggers just yet. However, it occurred to me that I could use a similar trick to the recursive materialised path view. Thus, we have a Closure View. We will start with the Django models: {% highlight python %} class Node(models.Model): node_id = models.AutoField(primary_key=True) parent = models.ForeignKey('tree.Node', related_name='children', null=True, blank=True) descendants = models.ManyToManyField('tree.Node', related_name='ancestors', through='tree.Closure') class Meta: app_label = 'tree' class Closure(models.Model): path = ArrayField(base_field=models.IntegerField(), primary_key=True) ancestor = models.ForeignKey('tree.Node', related_name='+') descendant = models.ForeignKey('tree.Node', related_name='+') depth = models.IntegerField() class Meta: app_label = 'tree' managed = False {% endhighlight %} You may notice I have a `path` column. I'm using this for the primary key, and it may turn out to be useful later. Let's have a look at … -
Django Model Inheritance - Multi-Table Inheritance
In the last post we talked about Model Inheritance with regards to Abstract Model Classes, it was a great introduction into using OOP with your models to keep your code slim and tidy. You can read it at: Django Abstract Base Class - Model Inheritance In this post we are going to discuss Multi-Table Inheritance. We will create a base model, that is not an abstract model, and inherit from the model. Then we are going to show you how to get and reference data from that models inheritance. Multi Table Inheritance When we talk about multi-table inheritance we are referring to having a top level table with all the fields that are core to that context. Then we are going to have other tables with the more specific fields. You select from the table you want, and then do a join on a relationship to get the parent table data. Since Django does this through models and code, we will talk about it in those terms. In our example we are going to have a Ticket Model. class Ticket(models.Model): title = models.CharField(max_length=255, blank=True) description = models.TextField(blank=True) name = models.CharField(max_length=255, blank=True) This model is a good piece of code because … -
ShipIt Day Recap: Q1 2016
Last Friday, the Cakti set aside regular client projects for our quarterly ShipIt Day, a chance for personal development and independent projects. People work individually or in groups to flex their creativity, tackle interesting problems, or expand their personal knowledge. This quarter’s ShipIt Day saw everything from cat animations to improvements on our Taylor Swift lyric generator app. Read about the various ShipIt Day projects for Q1 of 2016 below. Neil Ashton worked with the open source DemocracyOS, a platform for collaborative decision making. The platform is used around the world to increase participation in democratic systems. Neil took a look at the basic web app stack for the platform and submitted several pull requests to fix bugs in that system. All of his pull requests have since been approved, making Neil an official contributor to DemocracyOS! Calvin Spealman went into ShipIt Day with the intention of building a story generator. However, after running into a roadblock late Thursday evening, he transitioned instead to work on frontend tooling upgrades and related documentation in Caktus’ Django project template. In the meantime, Vinod upgraded one of Calvin’s projects to the latest version of Margarita. This enabled Calvin to demonstrate the new frontend … -
10 Popular Websites Built With Django
What is the framework Regardless of the sphere you work in, one of your most important tasks is to create a fast, good-looking website. Today, almost every business needs a website, which acts as a sort of business card for a company or online service. It helps you engage with customers, promote your business, increase sales and so on. In every case, the website should be fast, scalable and dynamic. When creating a website, you typically need to work with roughly the same set of basic components: ways to manage user authorizations (account creation, login); a user dashboard; file downloading and uploading, etc. If the tasks are the same, why not make them easier, and thereby reduce the cost of development? With this in mind, web frameworks appeared on the scene as a set of components designed to facilitate and simplify website creation. Django Advantages This web framework is intended to create highly scalable web applications or websites with a constantly growing audience (e.g. content-based or news sites). Django perfectly works as is and provides users with a range of options to create Python-based web-applications including a user dashboard, various database supports (SQLite, PostgresSQL, MySQL), admin functions, and more. Famous … -
hasattr() Considered Harmful
Don’t use Python hasattr() unless you want its quirks or are writing Python 3-only code. -
Django CMS Plugin Authenticated User Variations
Django CMS Plugin Authenticated User Variations -
Basics of Ember.js application development
After setting up the base of our ember application we can start doing something more with it. For my tutorials I've picked AdminLTE template to make a admin panel alike application. -
GeoDjango and Leaflet.js- part two
This is the second post from GeoDjango i Leaflet.js series. You can find the previous post under this link. After loading data to GeoDjango application now, it's time to present it to the user. You can use django template tag like {{object}} but I think it's better to provide api endpoints. I will be using GeoDjango builtin GeoJSON serializer. To do this declare new views in views.py: from django.http import HttpResponse from django.core.serializers import serialize from .models import Point, Voivodeship def points_view(request): points_as_geojson = serialize('geojson', Point.objects.all()) return HttpResponse(points_as_geojson, content_type='json') def wojewodztwa_view(request): voivodeships_as_geojson = serialize('geojson', Voivodeship.objects.all()) return HttpResponse(voivodeships_as_geojson, content_type='json') GeoJSON is open format for encoding geographical data. It's based on JSON. Then add lines to urls.py: from django.conf.urls import include, url from django.contrib import admin from voivodeships.views import points_view, voivodeships_view urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^points.data/', points_view, name='points'), url(r'^voivodeships.data/', voivodeships_view, name='voivodeships'), ] As you can see GeoDjango displays data from database in GeoJSON: It's nice but end user need to see results on the map not in JSON format so I use Leaflet.js. You can download leaflet.js from the web page but there is a better way: django-leaflet. It's django application with allows you embed leaflet to django project. Install it … -
GeoDjango and Leaflet.js- part two
This is the second post from GeoDjango i Leaflet.js series. You can find the previous post under this link. After loading data to GeoDjango application now, it's time to present it to the user. You can use django template tag like {{object}} but I think it's better to provide api endpoints. I will be using GeoDjango builtin GeoJSON serializer. To do this declare new views in views.py: from django.http import HttpResponse from django.core.serializers import serialize from .models import Point, Voivodeship def points_view(request): points_as_geojson = serialize('geojson', Point.objects.all()) return HttpResponse(points_as_geojson, content_type='json') def wojewodztwa_view(request): voivodeships_as_geojson = serialize('geojson', Voivodeship.objects.all()) return HttpResponse(voivodeships_as_geojson, content_type='json') GeoJSON is open format for encoding geographical data. It's based on JSON. Then add lines to urls.py: from django.conf.urls import include, url from django.contrib import admin from voivodeships.views import points_view, voivodeships_view urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^points.data/', points_view, name='points'), url(r'^voivodeships.data/', voivodeships_view, name='voivodeships'), ] As you can see GeoDjango displays data from database in GeoJSON: It's nice but end user need to see results on the map not in JSON format so I use Leaflet.js. You can download leaflet.js from the web page but there is a better way: django-leaflet. It's django application with allows you embed leaflet to django project. Install it … -
GeoDjango and Leaflet.js- part two
How to setup basic GeoDjango application second part. -
Django and Angular - Setting up Base Angular App
Learn what it takes to get the basics of an angular app going with Django. See how simple it is to get started.Watch Now... -
Disabling Migrations While Testing
If you have a large Django 1.7+ project with a lot of migrations running test even with --keepdb can be slow just because the new migration framework has to order the migrations even if there is nothing to do. After a few attempts I have found something which works pretty well for me. In your testing setting you can include the following: class DisableMigrations(object): def __contains__(self, item): return True def __getitem__(self, item): return "notmigrations" MIGRATION_MODULES = DisableMigrations() I have found related suggestions on the Django mailing list. Both ideas are presented on Stackoverflow.