From b8469deb09ccc2f3bc4080983f75916d4b1e7c55 Mon Sep 17 00:00:00 2001 From: Nazar Kotjuk Date: Mon, 26 Oct 2015 13:25:00 +0200 Subject: [PATCH] Article refactor --- accounts/models.py | 57 +++++++------- article/forms.py | 9 +-- article/management/__init__.py | 1 - article/management/commands/__init__.py | 1 - article/management/commands/article_load.py | 62 --------------- .../management/commands/articles_from_blog.py | 77 ------------------- .../management/commands/articles_from_old.py | 63 --------------- article/management/commands/news_from_old.py | 77 ------------------- .../management/commands/news_generate_file.py | 45 ----------- article/management/commands/update_news.py | 69 ----------------- article/models.py | 23 +++++- article/signals.py | 6 -- article/tests.py | 16 ---- article/urls.py | 48 ++++++++---- article/views.py | 49 +++++++----- theme/views.py | 10 +-- 16 files changed, 119 insertions(+), 494 deletions(-) delete mode 100644 article/management/__init__.py delete mode 100644 article/management/commands/__init__.py delete mode 100644 article/management/commands/article_load.py delete mode 100644 article/management/commands/articles_from_blog.py delete mode 100644 article/management/commands/articles_from_old.py delete mode 100644 article/management/commands/news_from_old.py delete mode 100644 article/management/commands/news_generate_file.py delete mode 100644 article/management/commands/update_news.py delete mode 100644 article/signals.py delete mode 100644 article/tests.py diff --git a/accounts/models.py b/accounts/models.py index 9db37057..f2dbdc87 100644 --- a/accounts/models.py +++ b/accounts/models.py @@ -78,16 +78,16 @@ class User(AbstractBaseUser, PermissionsMixin): db_index=True, ) username = models.CharField(verbose_name='Email', max_length=255, unique=True, db_index=True) - first_name = models.CharField(verbose_name='First name', max_length=255) - last_name = models.CharField(verbose_name='Last name', max_length=255) - rating = models.IntegerField(default=100)# добавить индекс в базе - url = models.SlugField(blank=True) - is_active = models.BooleanField(default=0) - is_staff = models.BooleanField(default=0) - is_admin = models.BooleanField(default=0) - date_joined = models.DateTimeField(auto_now_add=True) - date_registered = models.DateTimeField(blank=True, null=True) - date_modified = models.DateTimeField(auto_now=True) + first_name = models.CharField(verbose_name=_(u'First name'), max_length=255) + last_name = models.CharField(verbose_name=_(u'Last name'), max_length=255) + rating = models.IntegerField(verbose_name=_(u'Рейтинг'), default=100)# добавить индекс в базе + url = models.SlugField(verbose_name=_(u'Url'), blank=True) + is_active = models.BooleanField(verbose_name=_(u'Активный'), default=0) + is_staff = models.BooleanField(verbose_name=_(u'Сотрудник?'), default=0) + is_admin = models.BooleanField(verbose_name=_(u'Админ?'), default=0) + date_joined = models.DateTimeField(verbose_name=_(u'Дата создания'), auto_now_add=True) + date_registered = models.DateTimeField(verbose_name=_(u'Дата регистрации'), blank=True, null=True) + date_modified = models.DateTimeField(verbose_name=_(u'Изменен'), auto_now=True) #relations organiser = models.ForeignKey('organiser.Organiser', verbose_name='Организатор', blank=True, null=True, unique=True, @@ -95,7 +95,8 @@ class User(AbstractBaseUser, PermissionsMixin): translator = models.ForeignKey('translator.Translator', verbose_name='Переводчик', blank=True, null=True, unique=True, on_delete=models.PROTECT, related_name='user') - company = models.ForeignKey('company.Company', blank=True, null=True, related_name='users') + company = models.ForeignKey('company.Company', verbose_name=_(u'Компания'), blank=True, null=True, + related_name='users') position = models.CharField(verbose_name='Должность', max_length=255, blank=True) objects = UserManager() @@ -189,17 +190,17 @@ class Profile(models.Model): stores additional information about users """ user = models.OneToOneField(User) - country = models.ForeignKey('country.Country', verbose_name='Страна', blank=True, null=True, + country = models.ForeignKey('country.Country', verbose_name=_(u'Страна'), blank=True, null=True, on_delete=models.PROTECT, related_name='users') - city = models.ForeignKey('city.City', verbose_name='Город', blank=True, null=True, + city = models.ForeignKey('city.City', verbose_name=_(u'Город'), blank=True, null=True, on_delete=models.PROTECT) about_company = models.TextField(verbose_name=_(u'Описание компании'), blank=True) phone = models.BigIntegerField(verbose_name=_(u'Телефон'), blank=True, null=True) show_phone = models.NullBooleanField(verbose_name=_(u'Показывать телефон'), blank=True, null=True, default=1) - web_page = models.URLField(verbose_name='Вебсайт',blank=True) - about = models.TextField(verbose_name='О себе', blank=True) - avatar = models.ImageField(verbose_name='Фото', upload_to='accounts/avatar/', blank=True) - skype = models.CharField(blank=True, max_length=255) + web_page = models.URLField(verbose_name=_(u'Вебсайт'),blank=True) + about = models.TextField(verbose_name=_(u'О себе'), blank=True) + avatar = models.ImageField(verbose_name=_(u'Фото'), upload_to='accounts/avatar/', blank=True) + skype = models.CharField(verbose_name=_(u'Skype'), blank=True, max_length=255) facebook = models.URLField(verbose_name=_(u'Facebook'), blank=True, max_length=255) twitter = models.URLField(verbose_name=_(u'Twitter'), blank=True,max_length=255) linkedin = models.URLField(verbose_name=_(u'LinkedIn'), blank=True, max_length=255) @@ -216,10 +217,10 @@ class Calendar(models.Model): every user has one calendar """ user = models.OneToOneField(User) - expositions = models.ManyToManyField('exposition.Exposition', null=True) - conferences = models.ManyToManyField('conference.Conference', null=True) - seminars = models.ManyToManyField('seminar.Seminar', null=True) - webinars = models.ManyToManyField('webinar.Webinar', null=True) + expositions = models.ManyToManyField('exposition.Exposition', verbose_name=_(u'Выставки'), null=True) + conferences = models.ManyToManyField('conference.Conference', verbose_name=_(u'Конфеернции'), null=True) + seminars = models.ManyToManyField('seminar.Seminar', verbose_name=_(u'Семинары'), null=True) + webinars = models.ManyToManyField('webinar.Webinar', verbose_name=_(u'Вебинары'), null=True) def get_expos(self): # 1 query @@ -273,13 +274,13 @@ class Calendar(models.Model): class EventFilter(models.Model): user = models.OneToOneField(User) - theme = models.ManyToManyField('theme.Theme', null=True) - tag = models.ManyToManyField('theme.Tag', null=True) - area = models.ManyToManyField('country.Area', null=True) - country = models.ManyToManyField('country.Country', null=True) - city = models.ManyToManyField('city.City', null=True) - fr = models.DateField(blank=True, null=True) - to = models.DateField(blank=True, null=True) + theme = models.ManyToManyField('theme.Theme', verbose_name=_(u'Тематики'), null=True) + tag = models.ManyToManyField('theme.Tag', verbose_name=_(u'Теги'), null=True) + area = models.ManyToManyField('country.Area', verbose_name=_(u'Геограифческие зоны'), null=True) + country = models.ManyToManyField('country.Country', verbose_name=_(u'Страны'), null=True) + city = models.ManyToManyField('city.City', verbose_name=_(u'Города'), null=True) + fr = models.DateField(blank=True, verbose_name=_(u'с'), null=True) + to = models.DateField(blank=True, verbose_name=_(u'до'), null=True) def get_queryset(self): """ diff --git a/article/forms.py b/article/forms.py index 08f243a7..248485cc 100644 --- a/article/forms.py +++ b/article/forms.py @@ -1,15 +1,12 @@ # -*- coding: utf-8 -*- from django import forms from django.conf import settings -from ckeditor.widgets import CKEditorWidget -from django.core.exceptions import ValidationError from django.forms.util import ErrorList from django.utils.translation import ugettext as _ -#functions +from ckeditor.widgets import CKEditorWidget from functions.translate import fill_with_signal from functions.files import check_tmp_files from functions.form_check import translit_with_separator -#models from models import Article from accounts.models import User from theme.models import Theme, Tag, ThemeBlog @@ -97,14 +94,13 @@ class BlogForm(forms.Form): else: return [] + class NewsForm(BlogForm): type = Article.news exposition = forms.CharField(label=u'Выставка', widget=forms.HiddenInput(), required=False) conference = forms.CharField(label=u'Конференция', widget=forms.HiddenInput(), required=False) theme = forms.ModelMultipleChoiceField(label='Тематики', queryset=Theme.objects.all(), required=False, widget=forms.SelectMultiple(attrs={'style':'width: 550px'})) - #exposition = forms.ModelChoiceField(label = u'Выставка', required=False, queryset=Exposition.objects.all()) - #conference = forms.ModelChoiceField(label = u'Конференция', required=False, queryset=Conference.objects.all()) def save(self, author, article=None): article = super(NewsForm, self).save(author, article) @@ -135,6 +131,7 @@ class NewsForm(BlogForm): except Conference.DoesNotExist: return None + class ArticleForm(forms.Form): """ Create Article form for creating conference diff --git a/article/management/__init__.py b/article/management/__init__.py deleted file mode 100644 index 3ed9fd0f..00000000 --- a/article/management/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__author__ = 'root' diff --git a/article/management/commands/__init__.py b/article/management/commands/__init__.py deleted file mode 100644 index 3ed9fd0f..00000000 --- a/article/management/commands/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__author__ = 'root' diff --git a/article/management/commands/article_load.py b/article/management/commands/article_load.py deleted file mode 100644 index 70130815..00000000 --- a/article/management/commands/article_load.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -import xlrd -from django.core.management.base import BaseCommand -from django.conf import settings -from article.models import Article -from import_xls.excel_settings import article_sett -from django.db import IntegrityError - - -NEWS_FILE = settings.MEDIA_ROOT+'/import/news.xls' - - -class Command(BaseCommand): - def handle(self, *args, **options): - - f = open(NEWS_FILE, 'r') - book = xlrd.open_workbook(file_contents=f.read()) - sheet = book.sheet_by_index(0) - row_list = [sheet.row_values(row_number) for row_number in range(sheet.nrows)] - labels = [label for label in row_list[0]] - existing = 0 - for row_number, row in enumerate(row_list[2:]): - - published = row[4] - if row[0] != '': - # in first column ids - try: - object = Article.objects.language('ru').get(id=int(row[0])) - object.type = Article.news - object.save() - print(object.type) - continue - except ValueError: - - object = Article(type=Article.news) - object.translate('ru') - except Article.DoesNotExist: - object = Article(id= int(row[0])) - object.translate('ru') - existing += 1 - else: - # if id blank - its a new place - object = Article(type=Article.news) - object.translate('ru') - - for col_number, cell in enumerate(row): - - label = labels[col_number] - setting = article_sett.get(label) - if setting is None: - continue - - field_name = setting['field'] - func = setting.get('func') - value = func(cell) - setattr(object, field_name, value) - object.publish_date = published - try: - object.save() - except Exception, e: - print(e) - diff --git a/article/management/commands/articles_from_blog.py b/article/management/commands/articles_from_blog.py deleted file mode 100644 index f75ae65e..00000000 --- a/article/management/commands/articles_from_blog.py +++ /dev/null @@ -1,77 +0,0 @@ -# -*- coding: utf-8 -*- -import MySQLdb -from MySQLdb.cursors import DictCursor -from django.core.management.base import BaseCommand, CommandError -from functions.translate import fill_with_signal -from article.models import Article -from accounts.models import User -from theme.models import Theme,Tag - - -class Command(BaseCommand): - def handle(self, *args, **options): - db = MySQLdb.connect(host="localhost", - user="debian-sys-maint", - passwd="LPoEhMvzURQoH1aJ", - db="expomap_old_blog", - charset='utf8', - cursorclass=DictCursor) - - cursor = db.cursor() - - sql = """SELECT post.post_date as publish_date, - post.post_content as description, - post.post_modified as modified, - post.post_title as main_title, - post.post_name as slug, - tag.name as tag_name - FROM wp_posts post - INNER JOIN wp_term_relationships rel ON rel.object_id = post.ID - INNER JOIN wp_terms tag ON tag.term_id=rel.term_taxonomy_id - WHERE post_status = "publish";""" - - cursor.execute(sql) - result = cursor.fetchall() - user = User.objects.get(id=1) - - tags = {x.name: x.id for x in Tag.objects.language('ru')} - - clear_result = {} - - errors = [] - for a in result: - if a.get('tag_name') in tags.keys(): - tag_id = tags[a['tag_name']] - a['tag_id'] = [tag_id] - print a - else: - tag_id = None - - if not clear_result.get(a['main_title']): - clear_result[a['main_title']] = a - else: - if clear_result[a['main_title']].get('paid_id') and tag_id: - clear_result[a['main_title']]['tag_id'].append(tag_id) - - - for a in clear_result.values(): - article = Article(type=1, - created = a['publish_date'], - publish_date= a['publish_date'], - modified = a['modified'], - ) - article.author = user - article.translate('ru') - article.main_title = a['main_title'] - article.description = a['description'] - article.slug = a['slug'] - if a.get('tag_id'): - article.tag = [Tag.objects.language('ru').get(id=id) for id in a['tag_id']] - try: - article.save() - except Exception as e: - errors.append(e) - - print errors - - diff --git a/article/management/commands/articles_from_old.py b/article/management/commands/articles_from_old.py deleted file mode 100644 index f2034aa2..00000000 --- a/article/management/commands/articles_from_old.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -import MySQLdb -from MySQLdb.cursors import DictCursor -from django.core.management.base import BaseCommand, CommandError -from functions.translate import fill_with_signal -from article.models import Article -from accounts.models import User - - -class Command(BaseCommand): - def handle(self, *args, **options): - db = MySQLdb.connect(host="localhost", - user="kotzilla", - passwd="qazedc", - db="old_expomap", - charset='utf8', - cursorclass=DictCursor) - cursor = db.cursor() - - sql = """SELECT articles_description.articles_id as id , - articles_description.articles_name as main_title, - articles_description.articles_description as description, - articles.authors_id as author, - articles_description.articles_intro as preview, - articles.articles_date_added as created, - articles.articles_last_modified as modified, - articles.articles_date_available as publish_date, - articles_description.articles_head_title_tag as title, - articles_description.articles_head_desc_tag as descriptions, - articles_description.articles_head_keywords_tag as keywords - - FROM `articles_description` - JOIN articles - ON articles_description.articles_id=articles.articles_id""" - - cursor.execute(sql) - - result = cursor.fetchall() - user = User.objects.get(id=1) - Article.objects.blogs().delete() - for a in result: - article = Article(type=Article.blog, - id=a['id'], - created=a['created'], - modified=a['modified'], - publish_date=a['publish_date']) - - article.author = user - - article.translate('ru') - article.main_title = a['main_title'] - article.preview = a['preview'] - article.description = a['description'] - article.title = a['title'] - article.keywords = a['keywords'] - if len(a['descriptions'])<255: - article.descriptions = a['descriptions'] - article.save() - print(article) - - #print(a['main_title']) - - diff --git a/article/management/commands/news_from_old.py b/article/management/commands/news_from_old.py deleted file mode 100644 index aac5f958..00000000 --- a/article/management/commands/news_from_old.py +++ /dev/null @@ -1,77 +0,0 @@ -# -*- coding: utf-8 -*- -import datetime -import MySQLdb -from MySQLdb.cursors import DictCursor -from django.core.management.base import BaseCommand, CommandError -from functions.translate import fill_with_signal -from article.models import Article -from accounts.models import User -from django.db import IntegrityError - -class Command(BaseCommand): - def handle(self, *args, **options): - db = MySQLdb.connect(host="localhost", - user="expomap", - passwd="7FbLtAGjse", - db="old_db", - charset='utf8', - cursorclass=DictCursor) - cursor = db.cursor() - sql = """SELECT news_id as id , - headline as main_title, - content as description, - cid as author, - date_added as created - - FROM `payed_news` - WHERE status = 1 - order by created DESC""" - - cursor.execute(sql) - - result = cursor.fetchall() - user = User.objects.get(id=1) - now = datetime.datetime.now() - #Article.objects.news().delete() - - for a in result: - title = a['main_title'] - id = a['id'] - published = a['created'] - #try: - # news = Article.objects.get(id=id) - #except Article.DoesNotExist: - # continue - - #news.publish_date = published - #news.save() - - if len(a['main_title'])>255 or not a['main_title']: - continue - - - article = Article(type=Article.news, - old_id=a['id'], - publish_date=a['created'], - created=now) - if a['author']: - try: - author = User.objects.get(id=a['author']) - except User.DoesNotExist: - author = user - else: - author = user - - article.author = author - - article.translate('ru') - article.main_title = a['main_title'] - article.description = a['description'] - try: - article.save() - print(article) - except : - print ('error. id:%d'%a['id']) - - #print(a['main_title']) - diff --git a/article/management/commands/news_generate_file.py b/article/management/commands/news_generate_file.py deleted file mode 100644 index 57af5a16..00000000 --- a/article/management/commands/news_generate_file.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- -import MySQLdb -from MySQLdb.cursors import DictCursor -from django.core.management.base import BaseCommand, CommandError -from functions.translate import fill_with_signal -from article.models import Article -from accounts.models import User -from django.db import IntegrityError -import xlwt -from django.utils import translation -from django.conf import settings - -class Command(BaseCommand): - def handle(self, *args, **options): - translation.activate('en') - - workbook = xlwt.Workbook(encoding = 'utf8') - worksheet = workbook.add_sheet('My Worksheet') - - font = xlwt.Font() - font.name = 'Times New Roman' - font.bold = True - - style = xlwt.XFStyle() - # Create the Style - style.font = font - - qs = Article.objects.news() - worksheet.write(0, 0, 'id') - worksheet.write(0, 1, 'url') - worksheet.write(0, 2, 'title') - - row = 1 - for a in qs: - print a.id - url = a.slug - id = a.id - name = a.main_title - - worksheet.write(row, 0, id) - worksheet.write(row, 1, url) - worksheet.write(row, 2, name) - - row += 1 - workbook.save(settings.MEDIA_ROOT+'/import/exported_news.xls') \ No newline at end of file diff --git a/article/management/commands/update_news.py b/article/management/commands/update_news.py deleted file mode 100644 index 50329f04..00000000 --- a/article/management/commands/update_news.py +++ /dev/null @@ -1,69 +0,0 @@ -# -*- coding: utf-8 -*- -import MySQLdb -import datetime -from django.utils.translation import activate -from MySQLdb.cursors import DictCursor -from django.core.management.base import BaseCommand, CommandError -from django.conf import settings -import xlrd -from import_xls.utils import to_theme, to_tag -from functions.translate import fill_with_signal -from article.models import Article -from accounts.models import User -from django.db import IntegrityError -from exposition.models import Exposition - -NEWS_FILE = settings.MEDIA_ROOT+'/import/exported_news.xls' -BLOGS_FILE = settings.MEDIA_ROOT+'/import/blogs.xls' - - - -class Command(BaseCommand): - def handle(self, *args, **options): - activate('ru') - f = open(BLOGS_FILE, 'r') - book = xlrd.open_workbook(file_contents=f.read()) - sheet = book.sheet_by_index(0) - row_list = [sheet.row_values(row_number) for row_number in range(sheet.nrows)] - - - - - print(len(row_list)) - - - existing = 0 - - - for row_number, row in enumerate(row_list[2:]): - - id = int(row[0]) - if id == 49: - continue - - main_title = row[1] - theme = row[2] - tag = row[3] - description = row[4] - article = Article.objects.language('ru').get(id=id) - #article.main_title = main_title - #article.description = description - #article.save() - - - to_theme(article, theme) - to_tag(article, tag) - print(id) - """ - try: - expo = Exposition.objects.filter(translations__name=event)[0] - except IndexError: - expo = None - - if expo: - article.exposition = expo - article.save() - print(id) - """ - - diff --git a/article/models.py b/article/models.py index 7eb0153a..352d2f08 100644 --- a/article/models.py +++ b/article/models.py @@ -177,18 +177,27 @@ class Article(TranslatableModel): return self._get_next_or_previous_by_publish_date(False, **kwargs) def admin_url(self): + """ + returns url for admin pages + """ if self.type == 1: return '/admin/article/blog/%s' % self.slug elif self.type == 2: return '/admin/article/news/%s' % self.slug def get_permanent_url(self): + """ + returns object url on site(get_absolute_url analog) + """ if self.type == 1: return '/blogs/%s/' % self.slug elif self.type == 2: return '/news/%s/' % self.slug def get_blog_preview(self): + """ + returns preview(fildemodel) if it exist gor current object + """ preview = self.files.filter(purpose='preview') if preview: return preview[0] @@ -203,14 +212,26 @@ class Article(TranslatableModel): return None def get_catalog(self): + """ + get catalog for current objects + catalogs different for news and blogs + """ if self.type == 1: return '/blogs/' elif self.type == 2: return '/news/' def similar(self): + """ + returns list of articles with same type and themes + :return: + """ themes = [item['id'] for item in self.theme.all().values('id')] - return list(Article.objects.language().exclude(id=self.id).filter(type=self.type, publish_date__isnull=False, theme__in=themes).distinct().order_by('-publish_date')[:3]) + return list(Article.objects.language() + .exclude(id=self.id) + .filter(type=self.type, publish_date__isnull=False, theme__in=themes) + .distinct() + .order_by('-publish_date')[:3]) post_save.connect(post_save_handler, sender=Article) \ No newline at end of file diff --git a/article/signals.py b/article/signals.py deleted file mode 100644 index df3d2d3b..00000000 --- a/article/signals.py +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -from django.db.models.signals import post_save -from models import Article -from functions.signal_handlers import post_save_handler - -#post_save.connect(post_save_handler, sender=Article) diff --git a/article/tests.py b/article/tests.py deleted file mode 100644 index 501deb77..00000000 --- a/article/tests.py +++ /dev/null @@ -1,16 +0,0 @@ -""" -This file demonstrates writing tests using the unittest module. These will pass -when you run "manage.py test". - -Replace this with more appropriate tests for your application. -""" - -from django.test import TestCase - - -class SimpleTest(TestCase): - def test_basic_addition(self): - """ - Tests that 1 + 1 always equals 2. - """ - self.assertEqual(1 + 1, 2) diff --git a/article/urls.py b/article/urls.py index 073f7735..9488f8e5 100644 --- a/article/urls.py +++ b/article/urls.py @@ -3,22 +3,38 @@ from django.conf.urls import patterns, url from views import BlogList, NewsList, BlogDetail, NewsDetail, NewsTagCatalog, BlogsFilterCatalog urlpatterns = patterns('', - url(r'^blogs/tag/(?P.*)/page/(?P\d+)/$', BlogsFilterCatalog.as_view(), {'meta_id': 75, 'filter':'tag'}), - url(r'^blogs/theme/(?P.*)/page/(?P\d+)/$', BlogsFilterCatalog.as_view(), {'filter':'theme'}), - url(r'^blogs/page/(?P\d+)/$', BlogList.as_view(), {'meta_id':79}), - url(r'^blogs/tag/(?P.*)/$', BlogsFilterCatalog.as_view(), {'meta_id':75, 'filter':'tag'}), - url(r'^blogs/theme/(?P.*)/$', BlogsFilterCatalog.as_view(), {'filter':'theme'}), - url(r'^blogs/$', BlogList.as_view(), {'meta_id':79}), + url(r'^blogs/tag/(?P.*)/page/(?P\d+)/$', BlogsFilterCatalog.as_view(), + {'meta_id': 75, 'filter': 'tag'}), + url(r'^blogs/theme/(?P.*)/page/(?P\d+)/$', BlogsFilterCatalog.as_view(), + {'filter': 'theme'}), + url(r'^blogs/page/(?P\d+)/$', BlogList.as_view(), + {'meta_id': 79}), + url(r'^blogs/tag/(?P.*)/$', BlogsFilterCatalog.as_view(), + {'meta_id': 75, 'filter': 'tag'}), + url(r'^blogs/theme/(?P.*)/$', BlogsFilterCatalog.as_view(), + {'filter': 'theme'}), + url(r'^blogs/$', BlogList.as_view(), + {'meta_id': 79}), - url(r'^news/tag/(?P.*)/(?P\d+)/(?P.*)/page/(?P\d+)/$', NewsTagCatalog.as_view(), {'meta_id':77}), - url(r'^news/tag/(?P.*)/(?P\d+)/page/(?P\d+)/$', NewsTagCatalog.as_view(), {'meta_id':76}), - url(r'^news/tag/(?P.*)/page/(?P\d+)/$', NewsTagCatalog.as_view(), {'meta_id':74}), - url(r'^news/tag/(?P.*)/(?P\d+)/(?P.*)/$', NewsTagCatalog.as_view(), {'meta_id':77}), - url(r'^news/tag/(?P.*)/(?P\d+)/$', NewsTagCatalog.as_view(), {'meta_id':76}), - url(r'^news/tag/(?P.*)/$', NewsTagCatalog.as_view(), {'meta_id':74}), - url(r'^news/page/(?P\d+)/$', NewsList.as_view(), {'meta_id':78}), - url(r'^news/$', NewsList.as_view(), {'meta_id':78}), - url(r'^blogs/(?P.*)/$', BlogDetail.as_view(), {'meta_id':19}), - url(r'^news/(?P.*)/$', NewsDetail.as_view(), {'meta_id':19}), + url(r'^news/tag/(?P.*)/(?P\d+)/(?P.*)/page/(?P\d+)/$', NewsTagCatalog.as_view(), + {'meta_id': 77}), + url(r'^news/tag/(?P.*)/(?P\d+)/page/(?P\d+)/$', NewsTagCatalog.as_view(), + {'meta_id': 76}), + url(r'^news/tag/(?P.*)/page/(?P\d+)/$', NewsTagCatalog.as_view(), + {'meta_id': 74}), + url(r'^news/tag/(?P.*)/(?P\d+)/(?P.*)/$', NewsTagCatalog.as_view(), + {'meta_id': 77}), + url(r'^news/tag/(?P.*)/(?P\d+)/$', NewsTagCatalog.as_view(), + {'meta_id': 76}), + url(r'^news/tag/(?P.*)/$', NewsTagCatalog.as_view(), + {'meta_id': 74}), + url(r'^news/page/(?P\d+)/$', NewsList.as_view(), + {'meta_id': 78}), + url(r'^news/$', NewsList.as_view(), + {'meta_id':78}), + url(r'^blogs/(?P.*)/$', BlogDetail.as_view(), + {'meta_id': 19}), + url(r'^news/(?P.*)/$', NewsDetail.as_view(), + {'meta_id': 19}), ) diff --git a/article/views.py b/article/views.py index f62d3b5c..5cc1fe6d 100644 --- a/article/views.py +++ b/article/views.py @@ -1,22 +1,25 @@ # -*- coding: utf-8 -*- import json from django.views.generic import DetailView +from django.conf import settings +from django.shortcuts import get_object_or_404 +from django.utils.translation import ugettext as _ from functions.custom_views import ListView -from django.http import HttpResponse from models import Article -from forms import ArticleFilterForm, BlogFilterForm, NewsFilterForm -from theme.models import Tag, Theme, ThemeBlog +from forms import BlogFilterForm, NewsFilterForm +from theme.models import Tag, ThemeBlog from meta.views import MetadataMixin - - class NewsList(MetadataMixin, ListView): model = Article - template_name = 'article/news_list.html' - paginate_by = 10 + template_name = 'client/article/news_list.html' + paginate_by = settings.CLIENT_PAGINATION def get_queryset(self): + """ + filters queryset by get params if they exists + """ if self.request.GET: qs = self.model.objects.news() themes = self.request.GET.getlist('theme') @@ -32,9 +35,12 @@ class NewsList(MetadataMixin, ListView): return qs else: - return self.model.objects.news().filter(publish_date__isnull=False).order_by('-publish_date') + return self.model.objects.news().filter(publish_date__isnull=False) def get_context_data(self, **kwargs): + """ + add filter form to context + """ context = super(NewsList, self).get_context_data(object_list=self.object_list) if self.request.GET: filter_form = NewsFilterForm(self.request.GET) @@ -57,15 +63,18 @@ class NewsList(MetadataMixin, ListView): class NewsDetail(MetadataMixin, DetailView): model = Article slug_field = 'slug' - template_name = 'article/news.html' + template_name = 'client/article/news.html' class BlogList(MetadataMixin, ListView): model = Article - template_name = 'article/blog_list.html' - paginate_by = 10 + template_name = 'client/article/blog_list.html' + paginate_by = settings.CLIENT_PAGINATION def get_queryset(self): + """ + filters queryset by get params if they exists + """ if self.request.GET: qs = self.model.objects.blogs() @@ -85,6 +94,9 @@ class BlogList(MetadataMixin, ListView): return self.model.objects.blogs() def get_context_data(self, **kwargs): + """ + add filter form to context + """ context = super(BlogList, self).get_context_data(object_list=self.object_list) if self.request.GET: filter_form = BlogFilterForm(self.request.GET) @@ -104,19 +116,17 @@ class BlogList(MetadataMixin, ListView): return context - class BlogDetail(MetadataMixin, DetailView): model = Article slug_field = 'slug' - template_name = 'article/article.html' + template_name = 'client/article/article.html' -from exposition.views import ExpoCatalog -from django.conf import settings -from django.shortcuts import get_object_or_404 -from django.utils.translation import ugettext as _ - class NewsTagCatalog(MetadataMixin, ListView): + """ + returns queryset filtered by filtered_object and dates + filtered_object can be theme or tag + """ model = Article template_name = 'client/article/catalog.html' catalog_url = '/news/tag/' @@ -152,7 +162,6 @@ class NewsTagCatalog(MetadataMixin, ListView): self.month = {'text': monthes[month]['name'], 'link': '%s%s/%s/%s/'%(self.catalog_url, self.filter_object.url, year, month)} return qs - def get_context_data(self, **kwargs): context = super(NewsTagCatalog, self).get_context_data(**kwargs) context['filter_object'] = self.filter_object @@ -162,7 +171,6 @@ class NewsTagCatalog(MetadataMixin, ListView): return context - class BlogsFilterCatalog(MetadataMixin, ListView): model = Article template_name = 'client/article/catalog.html' @@ -206,7 +214,6 @@ class BlogsFilterCatalog(MetadataMixin, ListView): self.month = {'text': monthes[month]['name'], 'link': '%s%s/%s/%s/'%(self.catalog_url, self.filter_object.url, year, month)} return qs - def get_context_data(self, **kwargs): context = super(BlogsFilterCatalog, self).get_context_data(**kwargs) context['filter_object'] = self.filter_object diff --git a/theme/views.py b/theme/views.py index 29efa6bf..88545496 100644 --- a/theme/views.py +++ b/theme/views.py @@ -9,9 +9,9 @@ def get_tag(request): term = request.GET['term'].capitalize() qs = Tag.objects.language().distinct() if term: - qs = qs.filter(translations__name__contains=term) + qs = qs.filter(translations__name__contains=term)[:20] if themes: - qs = qs.filter(theme__id__in=themes).order_by('translations__name') + qs = qs.filter(theme__id__in=themes).order_by('translations__name')[:20] result = [{'id': tag.id, 'label': '%s (%s)'%(tag.name, tag.theme.name)} for tag in qs] result = sorted(result, key=lambda x:x['label']) @@ -25,7 +25,7 @@ def get_article_tags(request): qs = Tag.objects.language().exclude(article=None).filter(article__type=1).distinct() if term: qs = qs.filter(translations__name__contains=term) - result = [{'id': tag.id, 'label': '%s (%s)'%(tag.name, tag.theme.name)} for tag in qs] + result = [{'id': tag.id, 'label': '%s (%s)'%(tag.name, tag.theme.name)} for tag in qs[:20]] result = sorted(result, key=lambda x:x['label']) return HttpResponse(json.dumps(result), content_type='application/json') @@ -36,9 +36,9 @@ def get_news_tags(request): term = request.GET['term'].capitalize() qs = Tag.objects.language().exclude(article=None).filter(article__type=2).distinct() if term: - qs = qs.filter(translations__name__contains=term) + qs = qs.filter(translations__name__contains=term)[:20] if themes: - qs = qs.filter(theme__id__in=themes).order_by('translations__name') + qs = qs.filter(theme__id__in=themes).order_by('translations__name')[:20] result = [{'id': tag.id, 'label': '%s (%s)'%(tag.name, tag.theme.name)} for tag in qs] result = sorted(result, key=lambda x:x['label'])