########################################### # models.py ########################################### # -*- coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User import datetime # Модель категории новостей class Category(models.Model): # Поля новостей title = models.CharField(u'Название', max_length=250, help_text=u'Максимум 250 символов.') slug = models.CharField(max_length=60, help_text=u'Максимум 60 символов.') description = models.TextField(u'Описание') class Meta: verbose_name_plural = u"Категории" ordering = ['title'] def get_absolute_url(self): return "/categories/%s/" % self.slug def __unicode__(self): return '%s %s' % (self.title, self.description) # Модель новостей class News(models.Model): LIVE_STATUS = 1 DRAFT_STATUS = 2 HIDDEN_STATUS = 3 STATUS_CHOICES = ( (LIVE_STATUS, u'Опубликована'), (DRAFT_STATUS, 'Черновик'), (HIDDEN_STATUS, 'Скрытая'), ) # Основная информация title = models.CharField(u'Заголовок', max_length=100, help_text=u'Максимум 100 символов.') author = models.ForeignKey(User, default=1, verbose_name=u"Автор") slug = models.CharField(max_length=60, help_text=u'Максимум 60 символов.') # Категории и опции categories = models.ManyToManyField(Category, verbose_name=u"Категория") enable_comments = models.BooleanField(u'Разрешить комментарии', default=True) status = models.IntegerField(u'Статус', choices=STATUS_CHOICES, default=LIVE_STATUS) # Текстовые поля intro = models.TextField(u'Интро') content = models.TextField(u'Текст') # Даты pub_date = models.DateTimeField(u'Дата создания', default=datetime.datetime.now) change_date = models.DateTimeField(u'Дата изменения', auto_now=True) class Meta: verbose_name_plural = u"Новости" permissions = ( # Идентификатор права Описание права ("can_view", "Может видеть скрытые"), ("cant_view", "Не может видеть скрытые"), ) def __unicode__(self): return '%s %s %s' % (self.title, self.content, self.author) @models.permalink def get_absolute_url(self): return ('butsch_news_news_article', (), { 'year': self.pub_date.strftime("%Y"), 'month': self.pub_date.strftime("%b").lower(), 'day': self.pub_date.strftime("%d"), 'slug': self.slug }) ########################################### # admin.py ########################################### # -*- coding: utf-8 -*- from butsch.news.models import News, Category from django.contrib import admin import datetime class NewsAdmin(admin.ModelAdmin): fieldsets = [ (u'Основные настройки', {'fields': ['title', 'categories', 'author']}), (u'Дата публикации', {'fields': ['pub_date'], 'classes': ['collapse']}), (u'Контент', {'fields': ['intro', 'content']}), (u'Дополнительные опции', {'fields': ['enable_comments', 'status']}), (u'Ключевое слово', {'fields': ['slug'], 'classes': ['collapse']}), ] prepopulated_fields = {'slug': ['title',]} list_display = ('title', 'author', 'pub_date', 'change_date', 'status') search_fields = ['title', 'author'] ordering = ('-pub_date',) admin.site.register(News, NewsAdmin) class CategoriesAdmin(admin.ModelAdmin): fieldsets = [ (u'Основные настройки', {'fields': ['title', 'description']}), (u'Ключевое слово', {'fields': ['slug'], 'classes': ['collapse']}), ] prepopulated_fields = {'slug': ['title',]} list_display = ('title', 'description') search_fields = ['title'] admin.site.register(Category, CategoriesAdmin) ########################################### # views.py ########################################### from django.shortcuts import get_object_or_404, render_to_response from butsch.news.models import News def news_index(request): return render_to_response('news/index.html', { 'object_list': News.objects.all() }) def news_article(request, year, month, day, slug): import datetime, time date_stamp = time.strptime(year+month+day, "%Y%b%d") pub_date = datetime.date(*date_stamp[:3]) article = get_object_or_404(News, pubn_date__year=pub_date.year, pub_date__month=pub_date.month, publ__day=pub_date.day, slug=slug) return render_to_response('news/article.html', { 'article': article }) ########################################### # root urls.py ########################################### from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^admin/', include(admin.site.urls)), (r'^news/', include('news.urls.news')), ) ########################################### # root news/urls/news.py ########################################### from django.conf.urls.defaults import * from butsch.news.models import News news_info_arch = { 'queryset': News.objects.all(), 'date_field': 'pub_date', 'make_object_list':True, } news_info = { 'queryset': News.objects.all(), 'date_field': 'pub_date', } urlpatterns = patterns('django.views.generic.date_based', (r'^(?P\d{4})/(?P\w{3})/(?P\d{2})/(?P[-\w]+)/$', 'object_detail', news_info, 'butsch_news_news_article'), (r'^(?P\d{4})/(?P\w{3})/(?P\d{2})/$', 'archive_day', news_info_arch), (r'^(?P\d{4})/(?P\w{3})/$', 'archive_month', news_info_arch), (r'^(?P\d{4})/$', 'archive_year', news_info_arch, 'butsch_news_archive_year'), (r'^$', 'archive_index', news_info, 'butsch_news_archive_index'), ) ########################################### # root /res/tpl/news_archive.html ########################################### {% if user.is_authenticated %}

Добро пожаловать, {{ user.username }}. Спасибо, что не забываете нас.

{% else %}

Добро пожаловать, незнакомец. Кто вы?

{% endif %} Раздел новостей

Раздел новостей

{% for news in latest %} {% if perms.news.can_view %}

{{ news.title }}

Дата публикации: {{ news.pub_date|date:"F j, Y" }}

Автор: {{ news.author }}

{{ news.intro|safe }}

Read full entry

{% else %} {% ifequal news.status 1 %}

{{ news.title }}

Дата публикации: {{ news.pub_date|date:"F j, Y" }}

Автор: {{ news.author }}

{{ news.intro|safe }}

Read full entry

{% endifequal %} {% endif %} {% endfor %} ########################################### # root /res/tpl/news_archive_year.html ########################################### Архив за {{ year }} год

Архив за {{ year }} год

{% for news in object_list %}

{{ news }}

Дата публикации: {{ news.pub_date|date:"F j, Y" }}

Автор: {{ news.author }}

{{ news.intro|safe }}

Read full entry

{% endfor %} ########################################### # root /res/tpl/news_detail.html ########################################### {{ object.title }}

{{ object.title }}

{{ object.content }}

########################################### # settings.py ########################################### DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('*****', '******'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'mysql' DATABASE_NAME = '*****' DATABASE_USER = 'root' DATABASE_PASSWORD = '*****' DATABASE_HOST = '' DATABASE_PORT = '' TIME_ZONE = 'America/Chicago' LANGUAGE_CODE = 'ru-Ru' SITE_ID = 1 inery. USE_I18N = True MEDIA_ROOT = '/home/*****/www/butsch/res/img' MEDIA_URL = '/media/' /". ADMIN_MEDIA_PREFIX = '/media/' SECRET_KEY = 'fx2oz5gn6a-#dp&+*2e(zo34-dubvu8pw8kuh13@flat(j_+q4' TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = '*****.urls' TEMPLATE_DIRS = ( '/home/butsch/www/*****/res/tpl', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.admindocs', '******.news', )