13.May
How to use Django
0
| 0 votes
Autor: bookkeeper
Chapter: Django

Django is a free web framework written in python. It's very to use!

Let's create a blog in less then 10min!

1. First create a project

django-admin.py startproject blog

Switch to folder "blog"

Start the dev server

./manage runserver 8000

Type: http://127.0.0.1:8000 in browser

2. Create a file "models.py"

 Create a model

from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=32)
    date = models.DateTimeField(auto_now_add=True)
    text = models.TextField()

3. Setup your database settings

Edit the file "settings.py"

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'test',                      # Or path to database file if using sqlite3.
        'USER': 'test',                      # Not used with sqlite3.
        'PASSWORD': 'password',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

4. "Install" the blog models

Add "blog" to INSTALLED_APPS

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'blog', #<-------------------------------
    # Uncomment the next line to enable the admin:
    #'django.contrib.admin',
)

5. Create a templates

Create folder "templates".

Switch to folder "templates". Create file "index.html"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>My Blog</title>
    </head>

<body>
    <div id="content">
    {% block content %}
    {% endblock %}
    </div>
</body>

</html

6. Setup the templates path

Edit "settings.py" file.

Import os at the top

Add path to TEMPLATES_DIRS

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(os.path.dirname(__file__),'templates'), # creates a absolute path
)

7. Create the blog tables

Run "./manage syncdb"

It will create the blog tables.
It will ask you to create a superuser, follow the instructions

8. Add a url pattern

Edit file "urls.py"

urlpatterns = patterns('',
    # Example:
    # (r'^blog/', include('blog.foo.urls')),
    (r'^, 'blog.views.index'), #<------------------- index/root entry

    # Uncomment the admin/doc line below and add 'django.contrib.admindocs' 
    # to INSTALLED_APPS to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    #(r'^admin/', include(admin.site.urls)),
)

9. Create a view

Create a file "views.py"

from django.shortcuts import render_to_response

def index(request):
    return render_to_response('index.html', locals())

Run the dev server: ./manage runserver 8000

10. Activate the admin

Uncomment "django.contrib.admin" in INSTALLED_APPS

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'blog',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin', #<<<------- uncommented
)

Edit "urls.py" file

from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
from django.contrib import admin #<<< uncomment this
admin.autodiscover() #<<< uncomment this

urlpatterns = patterns('',
    (r'^, 'blog.views.index'),
    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)), #<<< uncomment this
)

Run ./manage syncdb

11. Activate the module in admin

Create file "admin.py"

from django.contrib import admin
from blog.models import Blog

class AdminBlog(admin.ModelAdmin):
    pass

admin.site.register(Blog, AdminBlog)

Type "http://127.0.0.1:8000/admin" in your browser

Login as superuser which you choose before

Click on "Add" and create some posts

12. Fill the view with logic

from django.shortcuts import render_to_response
from blog.models import Blog

def index(request):
    entries = Blog.objects.all()
    return render_to_response('index.html', locals())

13. Show it in template

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>My Blog</title>
    </head>

<body>
    <div id="content">
    {% block content %}
        {% for e in entries %}
            {{ e.title }}<br/>
            {{ e.date }}<br/>
            {{ e.text }}<br/>
            <hr/>
        {% endfor %}

    {% endblock %}
    </div>
</body>

</html>

Type http://127.0.0.1:8000 in your browser and you see your blog!

We are done!

Wasn't that easy?!