Below you will find pages that utilize the taxonomy term “Django”
Django and NGINX in Docker
In this post we will run Django application behind a NGINX webserver, which is a very common practice in production.
Django CRUD (Create, Retrieve, Update, Delete)
One of the most common task when developing web application is to write create, read, update and delete functionality (CRUD) for each table you have.
In this post I briefly cover the step needed to create a CRUD app in Django, the steps we will need are:
Django with Docker: Add Postgres
In the last post I covered starting a new Django project with Docker, and how to build a custom container image for my project, but what I haven’t covered is how to use a Database and how persist your data since all data stored in the container ephemeral and would only exist during the life span of the container.
Django with Docker: Build an Image
Docker is an interesting technology, although still young it gained a lot of buzz and momentum.
The last couple of weeks I started playing with Docker to see how can I use it for Django project development and deployment.
Django: How to pass an url as parameter of include
In Django web applications I usually have a single template file for navigation or bread crumb that I include from other template files, it is easy and straight forward to pass parameter to the included template file, some thing like:
{% include "nav.html" with title="title" object=my_object %}
But it would be a little tricker to send a URL as a parameter, i.e. you can’t write it:
{# WRONG DOESN'T WORK #}
{% include "nav.html" with title="title" link={% url 'book_edit'%} %}
But luckily Django have a decent and elegant solution, you can use “url” template function with “as” parameter, which will not display but will store it in a variable that you can use later in the include function:
Django CRUD Parent/Child Edition
I’ve written before about implementing CRUD operations on a single table in Django, and the post was very popular on my blog and I hope many people learned something from it.
The next logical step is to write a CRUD application with Parent/Child relationship, the application is bit more verbose but it follow the same simple logic used in the first post.
In fact I didn’t write a single application, I wrote five stand alone applications that shows different ways to implement CRUD operations:
Django Image and File Field Caveats
Every time I work with Image or File fields in Django I forget some tiny detail that waste 10-20 minutes until I remember what was I missing, I always say I will remember it next time but I never do! so I made a list of common errors I keep doing while working with Image/File fields:
For complete working project: (https://github.com/rayed/dj-imagefield-example)
Setting MEDIA_URL and MEDIA_ROOT
Make sure you set proper values for MEDIA_URL and MEDIA_ROOT in your settings.py, e.g. I use the following structure:
Django memory leak with gunicorn
If you have a long running job that leaks few bytes of memory it will eventually will consume all of your memory with time.
Django Themes (or where to put base.html?)
The Wrong Way
I used to create a new directory to hold common templates like “base.html”, and add it TEMPLATES_DIR in the settings.py file:
Translation in Django
Preparing Django project to support multiple langauges is easier than you think!
Django returning JSON for AJAX requests
In your views.py
you can have a page that return JSON data for AJAX request like this:
Setting Up Python and Supervisor on CentOS
CentOS default repository is very limited, and even if you install EPEL you will get old packages, in my case I needed to install Supervisor to manage my Django application, after trying to do it manually and through EPEL I ended up with the following setup.
Django Multiple Settings with Single File
Instead of having multiple settings files one for production and one for development and so on, I prefer to use an “if” statement with environment variable:
Django “render” vs “render_to_response”
Summary: Always use render
and not render_to_response
In Django you have more than one way to return a response, but many times I get confused between render
and render_to_response
, render_to_response seems shorter, so why not use it!
Implementing Login/Logout in Django
Update: add names and namespace to URLs
Implementing user authentication is fairly easy job in Django, many functionalities are already included in the standard Django installation, you can manage users using the default “admin” app the comes with Django.
Here I will show how implement Login/Logout feature by relying on Django built-in views.
Django Serving Static Files without a Web Server
UPDATE: Steps in this post isn’t correct, check the Django Themes post for better solution.
When deploying Django site it is always recommended to serve static files (e.g. js, css, img, static, media) using a normal web server instead of relying on Django built development server or Gunicorn.
But sometimes you want to test something quick and you don’t want to bother with installing or configuring a web server, the solution is to use the built-in django.views.static.serve view to serve the static files from Django it self:
Minimal Django Project: Part 2 … Flat Pages
In this step we will setup the Flatpage App, Flatpage allows you to create simple static pages from the Admin interface:
**mycms$ mkdir templates**
**mycms$ vi mycms/settings.py**
:
MIDDLEWARE_CLASSES = (
:
# Add Flatpage Middleware
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)
:
TEMPLATE_DIRS = (
:
'/Users/rayed/python/mycms/templates',
)
:
INSTALLED_APPS = (
:
# Add Flat Pages App
'django.contrib.flatpages',
:
)
:
**mycms$ vi mycms/urls.py**
:
# Your other patterns here
# SHOULD BE THE LAST RULE
urlpatterns += patterns('django.contrib.flatpages.views',
(r'^(?P<url>.*)$', 'flatpage'),
)
**mycms$ ./manage.py syncdb**
**mycms$ mkdir -p templates/flatpages**
**mycms$ vi templates/flatpages/default.html**
<!DOCTYPE html>
<html>
<head>
<title>{{ flatpage.title }}</title>
</head>
<body>
<h1>{{ flatpage.title }}</h1>
{{ flatpage.content }}
</body>
</html>
Now from the admin interface add a new page from “Flat pages” app, and you can view directly from the normal site.
Minimal Django Project: Part 1 … First Run
Update: Django 1.6+ don’t need any of these steps! it will work out of the box.
The following is the shortest way to create DB backed Django project, it uses SQLite as a backend, which make the setup very easy and fast.
I usually use for testing new Django modules or apps.
**$ django-admin.py startproject mycms**
**$ cd mycms**
**mycms$ chmod +x manage.py **
**mycms$ vi mycms/settings.py **
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': './mycms.db',
:
}
}
:
TIME_ZONE = 'Asia/Riyadh'
:
TEMPLATE_DIRS = (
PROJECT_ROOT + '/templates',
)
INSTALLED_APPS = (
:
'django.contrib.admin',
:
)
:
**mycms$ vi mycms/urls.py **
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
:
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
**mycms$ ./manage.py syncdb**
:
provide username, email, password for admin
:
**mycms$ ./manage.py runserver**
:
To access it from outside
:
**mycms$ ./manage.py runserver 0.0.0.0:8080**
To access it: Frontpage @ localhost Admin @ localhost
My Python and Django bookmarks
This a list of Django and Python websites I found useful, I hope you find it useful as well, and may be add to it in the comments:
- Django | Django documentation | Django documentation
- The Django Book
- Django Packages : Django Packages reusable apps, sites and tools directory
- 170+ Django conference videos | Equally True
- ubernostrum / django-registration — Bitbucket
- GoDjango.com – Going Through Django Screencasts
- Sourcefabric | Django Software Stack
- Drupal or Django? A Guide for Decision Makers | scot hacker's foobar blog
- <a HREF=“http://celeryproject.org/" “1335735065” >Homepage | Celery: Distributed Task Queue
- Haystack – Search for Django
- Ginger Tech Stack | Blog | Django Development | Lincoln Loop
- Django Best Practices — Django Best Practices
- 33 projects that make developing django apps awesome — elweb
- Brandon Konkle
- Django Advice / Steve Losh
- Auth tips and tricks
Django backend benchmark
I create small Django app and tried to benchmark it with different backends, here is the result:
Backend | Req/Sec |
---|---|
PostgreSQL | 68.41 |
PostgreSQL+pgpool | 116.12 |
MySQL | 127.61 |
Deploying Django
Django is a web framework written in Python language, my favourite computer programming language.
Python a language is really great language, easy to read and understand, and very easy to learn, but for me I always found setting up Python for web development as a challenge, socially if compare it to PHP, which almost works out of the box, actually most people think PHP works only in the web server and can’t work as stand alone application, search for PHP CLI if you are interested.
I will try here to document an easy Django deployment for my future reference and hopefully it will help others:
Django 1.0 released!
Django team released version 1.0 of the their web application framework, Django is written in Python.
I only tried Django for a week more than one year ago, and it was really amazing, and easy to create web application.
Even if you don’t write in Python I recommend you spend sometime to know it, may be walk through the tutorial. It has many inspiring and brilliant features you definitely need to know before select your next web framework.