Python Django Tutorial 5 – The built in Admin interface

1. Installing the Admin
Open the settings file and make sure that the following item is added to the INSTALLED_APPS set.

INSTALLED_APPS = (
    'django.contrib.admin',
)

2. Enable Admin URL’s in the project’s urls.py file
After importing the admin module, enable/add the following pattern in the list of urlpatterns:

from django.contrib import admin
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
]

3. Register the App’s models that need to be shown in Admin
Open the admin.py file created under the articles directory and register the models in this file.

from django.contrib import admin
from article.models import Article

# Register your models here.
admin.site.register(Article)

Now you should be able to add/edit/delete your articles from the admin panel. How cool is that!

Python – Ternary operator

Programming languages derived from C usually have following syntax:

(condition) ? (expression1) : (expression2)

The Python BDFL (creator of Python, Guido van Rossum) rejected it as non-Pythonic, since it is hard to understand for people not used to C. Moreover, the colon already has many uses in Python. So, when PEP 308 was approved, Python finally received its own shortcut conditional expression:

(expression1) if (condition) else (expression2)
e.g. reuse_appliances = True if use_existing_systems == 'True' else False

Python Django Tutorial 4(b) – Advanced views and urls

1. Defining URL’s within the App
So far, we had defined all URL’s in the main project’s urls.py file. But the purpose of having an app is that it can be a standalone module that can be plugged into any other project. For the same reason, it is nice to define all the URL’s related to the app contained with the app.

Create a new urls.py within the articles app. This is explained as per Django version 1.8. URL imports works in a different fashion for older Django versions.

from django.conf.urls import patterns, include, url
from article.views import articles, article

urlpatterns = [
	url(r'^all/$', articles, name='articles'),
	url(r'^get/(?P<article_id>\d+)/$', article, name='article'),
]

The part of code (?P<article_id>\d+) denotes a variable/parameter (?P) is named article_id will be of type digit of any length greater than 1 (\d+).

Now modify the urls.py within the project folder so that it is able to include the urls.py file that is created under the articles app.

urlpatterns = [
    url(r'^articles/', include('article.urls')),
}

The above denotes that anything starting with articles will look for the next segment of the URL within the article.urls file.

2. Creating views
Let’s define 2 more views in the views.py file under articles. The first one would take the article_id parameter from the URL and use it to show the article header and body, e.g. view for this URL http://127.0.0.1:8000/articles/get/1/

def article(request, article_id = 1):
	return render_to_response('article.html', {'article' : Article.objects.get(id=article_id)})

This view takes in a new parameter article_id apart form the standard request parameter. If you look back, the name of the parameter is defined within the URL (?P

\d+). The view calls the magical render_to_response by passing in the article object corresponding to the article_id.

The other view would list all the articles in the database, e.g. view for this url http://127.0.0.1:8000/articles/all/

def articles(request):
	return render_to_response('articles.html', {'articles' : Article.objects.all()})

This view passes all article objects to the template articles.html

3. Creating templates
The first template (article.html) takes in a single article object and displays it’s title and body.

<html>
<body>
<h1>{{ article.title }}</h1>
<p>{{ article.body }}</p>
</body>
</html>

The second template (articles.html) lists all the articles in the database with a link to access their individual article page.

<html>
<body>
{% for article in articles %}
<div>
<h2><a href="/articles/get/{{ article.id }}/">{{ article.title }}</a></h2>
<p>{{ article.body }}</p>
</div>
{% endfor %}
</body>
</html>

Python Django Tutorial 3 – views, simple urls and basic templates

1. Views
A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything, really.

Create a simple view hello that will take the request from url HOSTNAME/hello and return a simple HTML page with a custom welcome message. Create the following view function in the view.py file created by default in the Article app. You will have to import HttpResponse from django.http module in order to return the HtmlResponse from the view.

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def static_hello(request):
	name = 'Varun'
	html = "<html><body><h4>Hi %s,<br />This seems to have worked!</h4></body></html>" % name
	return HttpResponse(html)

2. URL
Now, we need to create a mapping so that Django can relate to the URL entered in the browser and pass on the processing to the hello view that we defined. We do this in the urls.py file created by default in the django_test project directory.

from article.views import hello
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),		#-- Added by default by Django
    url(r'^static-hello/', static_hello, name='static_hello')
]

Now navigate to 127.0.0.1:8000/static-hello/ and you’ll notice that the HTML response is showed on the page.

3. Template
A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. Create a new directory called templates in the project home (where you have manage.py). After creating this directory, modify the settings file so it can look for templates in this directory.

'DIRS': ['/Users/varun.verma/Work/scripts/python/setup/django-default/django_test/templates'],

The path for templates directory should be absolute and not relative.

Now let’s try to modify the view to render a response via a template. We’ll need a few imports to start with:

from django.template.loader import get_template

get_template is a helper function that helps get the template information from the settings file.

from django.template import Context

Context is important for Django template to understand how to render.

Create a new view in the views.py file:

def dynamic_hello(request):
	name = 'Varun'
	template = get_template('dynamic_hello.html')    # Load the template
	html = template.render(Context({'name' : name})) # Render the template with our local Context
	return HttpResponse(html)                        # Send HTTP Response back

Create a new file dynamic_hello.html in the templates directory:

<html>
<body>

<h4>
Hi {{ name }}, <br/>
This Dynamic Template seems to have worked.
</h4>
</body>
</html>

Add a new URL to the urls.py file that can invoke the new dynamic_hello view:

from article.views import static_hello, dynamic_hello
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^static-hello/', static_hello, name='static_hello'),
    url(r'^dynamic-hello/', dynamic_hello, name='dynamic_hello'),
]

Now navigate to 127.0.0.1:8000/dynamic-hello/ and you’ll notice that the dynamic HTML response is showed on the page.

4. TemplateView / Class based views
Class-based views provide an alternative way to implement views as Python objects instead of functions. Django provides an example of some classes which can be used as views. These allow you to structure your views and reuse code by harnessing inheritance and mixins.

from django.views.generic.base import TemplateView
class HelloTemplate(TemplateView):
	template_name = 'hello_class.html'

	def get_context_data(self, **kwargs):
		context = super(HelloTemplate, self).get_context_data(**kwargs)
		context['name'] = 'Varun'
		return context

Create a new file hello_class.html under the templates directory defined in the settings file

<html>
<body>

<h4>
Hi {{ name }}, <br/>
This Class Based view Template seems to have worked.
</h4>
</body>
</html>

Add new URL,

from article.views import HelloTemplate
url(r'^classview-hello/', HelloTemplate.as_view(), name='classview_hello'),

5. render_to_response
Last but not the least – render_to_response. We saw earlier a 3 step approach to taking a request and returning a Http Response – load a template, render the template with the Context and return Http Response. render_to_response can do all of that by itself.

from django.shortcuts import render_to_response
def simple_dynamic_hello(request):
	name = 'Varun'
	return render_to_response('dynamic_hello.html', {'name' : name})

Add new URL:

from article.views import simple_dynamic_hello
url(r'^simpledynamic-hello/', simple_dynamic_hello, name='dynamic_hello'),

Python Django Tutorial 2 – settings.py and database models

1. Setup settings.py

By default, it’s automatically setup to use SqlLite with the default db being db.sqlite3 file created in your django_test application directory created in Tutorial 1.

Set Language Code and Time Zone

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'

2. Create a new App inside the project
Navigate to the django_test directory and create a new app called article.

python manage.py startapp article

An empty file called __init__.py is created in the article directory. This tells python that article is a package that can be imported as a module. The other files that are created are views.py, tests.py and models.py. For now we will concentrate only on models.py.

3. Create models
Create a simple model for the article app in models.py

from django.db import models

# Create your models here.
class Article(models.Model):
	title = models.CharField(max_length=200)
	body = models.TextField()
	pub_date = models.DateTimeField('date published')
	likes = models.IntegerField()

4. Syncdb
Execute syncdb to build django tables and to setup the superuser.

python manage.py syncdb

Deprecated since version 1.7:
This command has been deprecated in favor of the migrate command, which performs both the old behavior as well as executing migrations. It is now just an alias to that command.

5. Add application to INSTALLED_APPS
You’ll soon realize that syncdb did not create the tables for the class defined in model.py. This is because the app isn’t listed under INSTALLED_APPS yet. In order to do that, open the settings.py file and add the following line to it:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'article',
)

6. Run migrations
After running syncdb, you’ll get a warning to use migrations. Use the following command to create and apply migrations

$ python manage.py makemigrations
Output:
Migrations for 'article':
  0001_initial.py:
    - Create model Article

$ python manage.py migrate
Output:
Running migrations:
  Rendering model states... DONE
  Applying article.0001_initial... OK

If you ever wanted to drop the application tables entirely from DB, run the following command:
python manage.py reset article

7. Using shell
To access the data, you can use the manage.py shell command to view, add or alter data.

8. Use the __unicode__ method to make the object data more meaningful

from django.db import models

# Create your models here.
class Article(models.Model):
	title = models.CharField(max_length=200)
	body = models.TextField()
	pub_date = models.DateTimeField('date published')
	likes = models.IntegerField()

	def __unicode__(self):
		return self.title

Python Django Tutorial 1 – Installing easy_install, virtualenv & django

1. Install easy_install via python-setuptools
easy_install – used to get python modules from PyPI (Python Package Index). easy_install script is part of the package called python-setuptools. The recommended way to bootstrap setuptools on any system is to download ez_setup.py and run it

sudo python ez_setup.py

using the target Python environment. The other way to install on some linux systems is to use sudo apt-get install python-setuptools

2. Use easy_install to download virtualenv
virtualenv is a tool to create isolated Python environments. virtualenv creates a folder which contains all the necessary executables to use the packages that a Python project would need. This keeps your global site-packages directory clean and manageable.

sudo easy_install virtualenv

Those are the 2 main applications that we need to install the sudo command. Once we’re done with those, we can start using virtualenv to cordon off our modules into a separate folder that won’t accept our main system. So we won’t have to use sudo anymore.

3. Create a new virtualenv directory for the django installation
Create a new directory for your virtualenv by running:

virtualenv --no-site-packages django-default

The –no-site-packages isolates your environment from the main site packages directory. You should get an output similar to:
New python executable in django-default/bin/python
Installing setuptools, pip, wheel…done.

4. Activate the new virtual environment
Now we need to activate the newly setup virtualenv so that any new installations from now one are put in our virtual environment and not in our root folder. In order to do that, run the following command:

source django-default/bin/activate

Now the shell will change the context into the current environment. Now any easy_install, pip will work in the current environment.

5. Install django in the virtualenv
Use easy_install to install django in the virtualenv.

easy_install Django

You will no longer require root/sudo permissions to do that because you’re now using this setup in your local environment. This will install the django-admin application in the bin directory.

6. Create a django project in the virtualenv
Use django-admin application to create the first django application:

django-admin.py startproject django_test

This will create a directory django_test with the project files. We have a manage.py file along with the project folder. The manage.py file is important to develop your application in terms of configuring your system, setting of your web server, etc

7. Run server using manage.py
Run your server by running the following command in your django project directory (django_test):

python manage.py runserver

You should get a similar output to ensure that your server is up and running:
Django version 1.8.2, using settings ‘django_test.settings’
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Navigate to http://127.0.0.1:8000/ from your browser and you should see a congratulations message signalling that your django site is up and running.

8. Deactivate/Exit the virtualenv
Just execute

deactivate

from the virtualenv shell to exit the virtualenv you’re working on and return to the main shell.