Примеры URLS - Controllers - Models - Views в Django
SETTINGS
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'C:/django/newsite/django.db',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
STATICFILES_DIRS = (
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
SECRET_KEY = 'zs4hv&i8nxj74@eedz82xjvhyaw3&x*!p#=)a=@@r3m+3ex=ij'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'newsite.urls'
TEMPLATE_DIRS = (
"C:/django/newsite/templates",
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'blog',
'books',
)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
URLS
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'newsite.views.home', name='home'),
url(r'^hello/$', 'views.hello'),
url(r'^time/$', 'views.current_datetime'),
url(r'^another-time-page/$', 'views.current_datetime'),
url(r'^time/plus/(\d{1,2})/$', 'views.hours_ahead'),
url(r'^blog/$', 'blog.views.archive'),
url(r'^meta/$', 'views.display_meta'),
url(r'^search-form/$', 'views.search_form'),
url(r'^search/$', 'views.search'),
url(r'^contact/$', 'views.contact'),
url(r'^image/$', 'views.get_image'),
url(r'^csv/$', 'views.unruly_passengers_csv'),
url(r'^color/$', 'views.show_color'),
url(r'^color/set/$', 'views.set_color'),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
VIEWS
# -*- coding: utf-8 -*-
from django.template import Template, Context
from django.template.loader import get_template
from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response
from books.models import Book
from forms import ContactForm
import datetime
import csv
def hello(request):
return HttpResponse("Здравствуй, мир!")
def current_datetime(request):
now = datetime.datetime.now()
# template = get_template("current_time.html")
# html = template.render(Context({"current_date": now}))
# return HttpResponse(html)
return render_to_response("dateapp/current_time.html", {"current_date": now, "current_section": 10})
def hours_ahead(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404()
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
html = "<html><body>Через %s часов будет %s.</body></html>" % (offset, dt)
return HttpResponse(html)
def display_meta(request):
values = request.META.items()
values.sort()
return render_to_response("meta/meta.html", {"values": values})
def search_form(request):
return render_to_response('search/search_form.html')
def search(request):
errors = []
if 'q' in request.GET:
q = request.GET['q']
if not q:
errors.append('Введите поисковый запрос.')
elif len(q) > 20:
errors.append('Введите не более 20 символов.')
else:
books = Book.objects.filter(title__icontains=q)
return render_to_response('search/search_results.html', {'books': books, 'query': q})
return render_to_response('search/search_form.html', {'errors': errors})
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(
cd['subject'],
cd['message'],
cd.get('e-mail', 'noreply@example.com'),
['siteowner@example.com' ],
)
return HttpResponseRedirect('/contact/thanks/')
else:
form = ContactForm(
initial={
'subject': 'Мне очень нравится ваш сайт!',
'e_mail': 'super@mail.ru',
'message': 'Ого-го!'
}
)
return render_to_response('search/contact_form.html', {'form': form})
def get_image(request):
image_data = open("C:/django/newsite/pic1.png", "rb").read()
return HttpResponse(image_data, mimetype="image/png")
UNRULY_PASSENGERS = [146,184,235,200,226,251,299,273,281,304,203,134,147]
def unruly_passengers_csv(request):
response = HttpResponse(mimetype="text/csv")
response['Content-Disposition'] = 'attachment'
filename = 'wild.csv'
writer = csv.writer(response)
writer.writerow(['Year', 'Unruly Airplane Passangers'])
for (year, num) in zip(range(1995,2007), UNRULY_PASSENGERS):
writer.writerow([year, num])
return response
def show_color(request):
if "favorite_color" in request.COOKIES and "fav_color" in request.session:
return HttpResponse("Ваш любимый цвет через cookie %s и через session %s" % (request.COOKIES["favorite_color"], request.session["fav_color"]))
else:
return HttpResponse("У вас нет любимого цвета.")
def set_color(request):
response = HttpResponse("Вы установили цвет.")
response.set_cookie("favorite_color", "blue")
request.session["fav_color"] = "red"
return response
FORMS
# -*- coding: utf-8 -*-
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100, label='Тема письма')
e_mail = forms.EmailField(required=False, label='Ваш адрес e-mail')
message = forms.CharField(widget=forms.Textarea, label='Сообщение')
def clean_message(self):
message = self.cleaned_data['message']
num_words = len(message.split())
if num_words < 4:
raise form.ValidationError("Слишком мало слов!")
return message
TEMPLATES
templates/dateapp/current_time.html
<html>
<body>
Сейчас {{current_date}}.
{% include "includes/nav.html" %}
</body>
</html>
templates/includes/nav.html
<div id="nav">Вы находитесь в секции: {{current_section}}</div>
templates/meta/meta.html
<table>
{% for k, v in values %}
<tr><td>{{k}}</td><td>{{v}}</td></tr>
{% endfor %}
<table>
templates/search/contact_form.html
<html>
<head>
<style type="text/css">
ul.errorlist {
margin: 0;
padding: 0;
}
.errorlist li {
background-color: red;
color: white;
display: block;
font-size: 10px;
margin: 0 0 3px;
padding: 4px 5px;
}
</style>
<title>Свяжитесь с нами</title>
</head>
<body>
<h1>Свяжитесь с нами</h1>
{% if form.errors %}
<p style="color: red;"> Исправьте следующие ошибки{{ form.errors|pluralize }}. </p>
{% endif %}
<form action="" method="post">
<div class="field">
{{ form.subject.errors }}
<label for="id_subject">Teмa:</label>
{{ form.subject }}
</div>
<div class="field">
{{ form.e_mail.errors }}
<label for="id_e-mail">Baш адрес e-mail:</label>
{{ form.e_mail }}
</div>
<div class="field">
{{ form.message.errors }}
<label for="id_message">Сообщение:</label>
{{ form.message }}
</div>
<input type="submit" value="0тправить">
</form>
</body>
</html>
templates/search/search_form.html
<html>
<head>
<title>Поиск</title>
</head>
<body>
{% if errors %}
<ul style="color: red;">
{% for error in errors %}
<li>{{error}}</li>
{% endfor %}
</ul>
{% endif %}
<form action="/search/" method="get">
<input type="text" name="q" />
<input type="submit" value="Найти" />
</form>
</body>
</html>
templates/search/search_results.html
<html>
<head>
<title>Результаты поиска</title>
</head>
<body>
<p>Вы искали: <strong>{{ query }}</strong></p>
{% if books %}
<p>Найдено {{ books|length }} книг{{ books|pluralize }}.</p>
<ul>
{% for book in books %}
<li>{{ book.title }}</li>
{% endfor %}
</ul>
{% else %}
<p>Книг, удовлетворяющих заданному критерию не найдено.</p>
{% endif %}
</body>
</html>
books/admin.py
from django.contrib import admin
from books.models import Publisher, Author, Book
class AuthorAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'email')
search_fields = ('first_name', 'last_name')
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publication_date',)
date_hierarchy = 'publication_date'
ordering = ('-publication_date',)
fields = ('title', 'authors', 'publisher', 'publication_date')
filter_horizontal = ('authors',)
raw_id_fields = ('publisher',)
admin.site.register(Publisher)
admin.site.register(Author, AuthorAdmin)
admin.site.register(Book, BookAdmin)
books/model.py
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
def __unicode__(self):
return self.name
def mycountry(self):
print self.country
class Meta:
ordering = ['name']
class Author(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=40)
email = models.EmailField(blank=True, verbose_name='e-mail')
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField(blank=True, null=True)
def __unicode__(self):
return self.title
blog/models.py
from django.db import models
from django.contrib import admin
class BlogPost(models.Model):
title = models.CharField(max_length = 150)
body = models.TextField()
timestamp = models.DateTimeField()
class Meta:
ordering = ('-timestamp',)
class BlogPostAdmin(admin.ModelAdmin):
list_display = ('title', 'body', 'timestamp')
admin.site.register(BlogPost, BlogPostAdmin)
blog/views.py
from django.template import loader, Context
from django.http import HttpResponse
from blog.models import BlogPost
def archive(request):
posts = BlogPost.objects.all()
template = loader.get_template("archive.html")
context = Context({'posts': posts})
return HttpResponse(template.render(context))
blog/templates/layout.html
<html>
<style type="text/css">
body { color: #efd; background: #453; padding: 0 5em; margin: 0 }
h1 { padding: 2em 1em; background: #675 }
h2 { color: #bf8; border-top: 1px dotted #fff; margin-top: 2em }
p { margin: 1em 0 }
</style>
<body>
<h1>newsite.example.com</h1>
{% block archive %}
{% endblock %}
</body>
</html>
blog/templates/archive.html
{% extends "layout.html" %}
{% block archive %}
{% for post in posts %}
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
<p>{{ post.timestamp|date:"l, F jS" }}</p>
{% endfor %}
{% endblock %}
Комментариев нет:
Отправить комментарий