среда, 27 марта 2013 г.

Django Paginator

views.py

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from blog.data.models import Entry

def index(request):
    entries = Entry.objects.published_entries().order_by('-id')
    paginator = Paginator(entries, 2)
    page_num = request.GET.get('page', 1)
    try:
        page = paginator.page(page_num)
    except EmptyPage:
        page = paginator.page(paginator.num_pages)
    except PageNotAnInteger:
        page = paginator.page(1)

    return render_to_response('homepage/index.html', {'page': page}, context_instance = RequestContext(request))

--------------------------------------------------------------------------------------------

index.html

{% extends "homepage/base.html" %}

{% block content %}
    <h3>Entries</h3>
    {% for entry in page.object_list %}
    <div>{{ entry.title }} - {{ entry.created }}</div>
    <div>{{ entry.text }}</div>
    <br />
    {% endfor %}
   
    {% if page.has_previous %}
    <a href="?page={{ page.previous_page_number }}">prev</a>
    {% endif %}
   
    | {{ page.number }} |
   
    {% if page.has_next %}
    <a href="?page={{ page.next_page_number }}">next</a>
    {% endif %}

   
{% endblock %}

вторник, 26 марта 2013 г.

Django MEDIA_URL in Templates

settings.py

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), 'static/'))

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/static/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

TEMPLATE_CONTEXT_PROCESSOR = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.media',
)

--------------------------------------------------------------------------------------------

views.py

from django.shortcuts import render_to_response
from blog.data.models import Entry
from django.template import RequestContext

def index(request):
    entries = Entry.objects.published_entries().order_by('-id')
    return render_to_response('homepage/index.html', {'entries': entries}, context_instance = RequestContext(request))

def about(request):
    return render_to_response('homepage/about.html', context_instance = RequestContext(request))

def contact(request):
    return render_to_response('homepage/contact.html', context_instance = RequestContext(request))

def archive(request):
    return render_to_response('homepage/archive.html', context_instance = RequestContext(request))

--------------------------------------------------------------------------------------------

base.html

<html>
<head>
    <title>{% block title %}{% endblock %}</title>
    {% block js %}{% endblock %}
    {% block css %}<link rel="stylesheet" href="{{ MEDIA_URL }}css/main.css" type="text/css" media="screen" />{% endblock %}
</head>
<body>
    <div id="top">My Blog</div>
    <div id="navi">{% block navi %}{% endblock %}</div>
    <div id="content">{% block content %}{% endblock %}</div>
    <div id="footer">{% block footer %}{% endblock %}</div>
</body>
</html>

Django Static files on Developer Server

base.html

<html>
<head>
    <title>{% block title %}{% endblock %}</title>
    {% block js %}{% endblock %}
    {% block css %}<link rel="stylesheet" href="/static/css/main.css" type="text/css" media="screen" />{% endblock %}
</head>
<body>
    <div id="top">My Blog</div>
    <div id="navi">{% block navi %}{% endblock %}</div>
    <div id="content">{% block content %}{% endblock %}</div>
    <div id="footer">{% block footer %}{% endblock %}</div>
</body>
</html>

--------------------------------------------------------------------------------------------

settings.py

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), 'static/'))

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/static/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.admin',
    'blog.data',
)

-------------------------------------------------------------------------------------------- 

urls.py

from django.conf.urls.defaults import patterns, include, url

from blog import settings

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', 'blog.homepage.views.index', name = 'homepage_index'),
    url(r'^about/$', 'blog.homepage.views.about', name = 'homepage_about'),
    url(r'^contact/$', 'blog.homepage.views.contact', name = 'homepage_contact'),
    url(r'^archive/$', 'blog.homepage.views.archive', name = 'homepage_archive'),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)

Django Urls from urls.py in Templates

urls.py

from django.conf.urls.defaults import patterns, include, url

from blog import settings

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', 'blog.homepage.views.index', name = 'homepage_index'),
    url(r'^about/$', 'blog.homepage.views.about', name = 'homepage_about'),
    url(r'^contact/$', 'blog.homepage.views.contact', name = 'homepage_contact'),
    url(r'^archive/$', 'blog.homepage.views.archive', name = 'homepage_archive'),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)

--------------------------------------------------------------------------------------------

index.html

{% extends "homepage/base.html" %}

{% block title %}My Blog Index{% endblock %}

{% block navi %}
<a href="{% url homepage_index %}">home</a> - <a href="{% url homepage_about %}">about</a> - <a href="{% url homepage_archive %}">archive</a> - <a href="{% url homepage_contact %}">contact</a>
{% endblock %}

{% block content %}
    <h3>Entries</h3>
    {% for entry in entries %}
    <div>{{ entry.title }} - {{ entry.created }}</div>
    <div>{{ entry.text }}</div>
    <br />
    {% endfor %}
{% endblock %}

{% block footer %}
2011 - MyBlog
{% endblock %}

Django Model Managers

data/managers.py

from django.db import models

class EntryManager(models.Manager):
    def published_entries(self):
        return self.model.objects.filter(published = True)

--------------------------------------------------------------------------------------------

data/models.py

#-*- coding: utf-8 -*-

from django.db import models
from blog.data.managers import EntryManager

class Entry(models.Model):
    created = models.DateTimeField(auto_now_add = True)
    updated = models.DateTimeField(auto_now = True)
    title   = models.CharField(max_length = 64)
    text    = models.TextField()
    published = models.BooleanField(db_index = True, default = True)
   
    objects = EntryManager()
   
    def __unicode__(self):
        return u'%s - %s' % (self.title, self.created)

--------------------------------------------------------------------------------------------

data/views.py

from django.shortcuts import render_to_response
from blog.data.models import Entry

def index(request):
    entries = Entry.objects.published_entries().order_by('-id')
    return render_to_response('homepage/index.html', {'entries': entries})

Comparison of Common Windows and Linux Commands

Command's PurposeMS-DOSLinuxBasic Linux Example
Copies filescopycpcp thisfile.txt /home/thisdirectory
Moves filesmovemvmv thisfile.txt /home/thisdirectory
Lists filesdirlsls
Clears screenclsclearclear
Closes prompt windowexitexitexit
Displays or sets datedatedatedate
Deletes filesdelrmrm thisfile.txt
"Echoes" output on the screenechoechoecho this message
Edits files with simple text editoreditpico[a]pico thisfile.txt
Compares the contents of filesfcdiffdiff file1 file2
Finds a string of text in a filefindgrepgrep this word or phrase thisfile.txt
Formats a disketteformat a: (if diskette is in A:)mke2fs (or mformat[b])/sbin/mke2fs /dev/fd0 (/dev/fd0 is the Linux equivalent of A:)
Displays command helpcommand /?man[c]man command
Creates a directorymkdirmkdirmkdir directory
View a filemoreless[d]less thisfile.txt
Renames a filerenmvmv thisfile.txt thatfile.txt[e]
Displays your location in the file systemchdirpwdpwd
Changes directories with a specified path (absolute path)cd pathnamecd pathnamecd /directory/directory
Changes directories with a relative pathcd ..cd ..cd ..
Displays the timetimedatedate
Shows amount of RAM and usememfreefree
Notes:
a. Pico is a simple text editor; other editors you can use in place of Pico include Emacs and vi.
b. This formats a disk for the DOS filesystem.
c. You can also use info for some commands.
d. The more pager can also be used to page through a file a screen at a time.
e. The mv command can both move a file and, if you want to rename a file in the same directory, you "move" that file to the same directory with a new name, as in this example.

вторник, 19 марта 2013 г.

Python Проверка существования файла

Данный Python код проверяет существование файла и возможность работы с ним.

from os import path, access, R_OK  # W_OK for write permission.

PATH='./file.txt'

if path.exists(PATH) and path.isfile(PATH) and access(PATH, R_OK):
    print "File exists and is readable"
else:
    print "Either file is missing or is not readable"