Enforce some pep8 code style

This commit is contained in:
Rodolphe Breard 2018-01-27 23:12:09 +01:00
parent e986389d25
commit 0b59b4b140
13 changed files with 105 additions and 24 deletions

View file

@ -26,7 +26,10 @@ SECRET_KEY = os.getenv('KHAGANAT_SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = bool(os.getenv('KHAGANAT_DEBUG', default='')) DEBUG = bool(os.getenv('KHAGANAT_DEBUG', default=''))
ALLOWED_HOSTS = [_ for _ in os.getenv('KHAGANAT_HOSTNAMES', default='').split(',') if _ != ''] ALLOWED_HOSTS = [
_ for _ in os.getenv('KHAGANAT_HOSTNAMES', default='').split(',')
if _ != ''
]
# Application definition # Application definition

View file

@ -16,7 +16,7 @@ Including another URLconf
from django.views.generic.base import RedirectView from django.views.generic.base import RedirectView
from django.conf.urls.i18n import i18n_patterns from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin from django.contrib import admin
from django.urls import include,path from django.urls import include, path
from pages.views import index from pages.views import index
urlpatterns = [ urlpatterns = [

View file

@ -1,5 +1,5 @@
from django.contrib import admin from django.contrib import admin
from .models import Source,Entry from .models import Source, Entry
admin.site.register(Source) admin.site.register(Source)
admin.site.register(Entry) admin.site.register(Entry)

View file

@ -1,5 +1,6 @@
from django.db import models from django.db import models
class Source(models.Model): class Source(models.Model):
name = models.CharField(max_length=128) name = models.CharField(max_length=128)
slug = models.CharField(max_length=128, unique=True) slug = models.CharField(max_length=128, unique=True)

View file

@ -4,5 +4,8 @@ from . import views
urlpatterns = [ urlpatterns = [
path('', views.IndexView.as_view(), name='log_index'), path('', views.IndexView.as_view(), name='log_index'),
path('<slug:source>/<int:year>/<int:month>/<int:day>/', views.EntriesView.as_view(), name='log_day'), path(
'<slug:source>/<int:year>/<int:month>/<int:day>/',
views.EntriesView.as_view(), name='log_day'
),
] ]

View file

@ -2,21 +2,41 @@ from django.db.models.functions import TruncDate
from django.db.models import Count from django.db.models import Count
from django.views import generic from django.views import generic
from django.conf import settings from django.conf import settings
from .models import Source,Entry from .models import Source, Entry
import datetime import datetime
class IndexView(generic.ListView): class IndexView(generic.ListView):
template_name = 'logs/index.html' template_name = 'logs/index.html'
context_object_name = 'sources' context_object_name = 'sources'
def get_queryset(self): def get_queryset(self):
now = datetime.date.today() now = datetime.date.today()
begin_date = now - datetime.timedelta(days=settings.KHAGANAT_LOGS_MAX_DAYS) start_date = now - datetime.timedelta(
end_date = now - datetime.timedelta(days=settings.KHAGANAT_LOGS_MIN_DAYS - 1) days=settings.KHAGANAT_LOGS_MAX_DAYS
)
end_date = now - datetime.timedelta(
days=settings.KHAGANAT_LOGS_MIN_DAYS - 1
)
out = [] out = []
for src in Entry.objects.filter(hidden=False, source__hidden=False, created__range=(begin_date, end_date)).values('source', 'source__name', 'source__slug').annotate(nb=Count('id')): qs = Entry.objects.filter(
src['stats'] = Entry.objects.filter(hidden=False, source=src['source'], created__range=(begin_date, end_date)).annotate(date=TruncDate('created')).values('date').annotate(nb=Count('date')).order_by('-date') hidden=False,
source__hidden=False,
created__range=(start_date, end_date)
).values('source', 'source__name', 'source__slug').annotate(
nb=Count('id')
)
for src in qs:
src['stats'] = Entry.objects.filter(
hidden=False,
source=src['source'],
created__range=(start_date, end_date)
).annotate(
date=TruncDate('created')
).values('date').annotate(nb=Count('date')).order_by('-date')
out.append(src) out.append(src)
return out return out
@ -27,18 +47,38 @@ class EntriesView(generic.ListView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['date'] = datetime.date(self.kwargs['year'], self.kwargs['month'], self.kwargs['day']) context['date'] = datetime.date(
context['source_channel'] = Source.objects.get(slug=self.kwargs['source']), self.kwargs['year'],
self.kwargs['month'],
self.kwargs['day']
)
context['source_channel'] = Source.objects.get(
slug=self.kwargs['source']
)
if isinstance(context['source_channel'], tuple): if isinstance(context['source_channel'], tuple):
context['source_channel'] = context['source_channel'][0] context['source_channel'] = context['source_channel'][0]
return context return context
def get_queryset(self): def get_queryset(self):
dt = datetime.date(self.kwargs['year'], self.kwargs['month'], self.kwargs['day']) dt = datetime.date(
self.kwargs['year'],
self.kwargs['month'],
self.kwargs['day']
)
now = datetime.date.today() now = datetime.date.today()
if (now - dt).days > settings.KHAGANAT_LOGS_MAX_DAYS or (now - dt).days < settings.KHAGANAT_LOGS_MIN_DAYS: out_of_bounds = any((
(now - dt).days > settings.KHAGANAT_LOGS_MAX_DAYS,
(now - dt).days < settings.KHAGANAT_LOGS_MIN_DAYS,
))
if out_of_bounds:
return Entry.objects.none() return Entry.objects.none()
src = Source.objects.get(slug=self.kwargs['source']) src = Source.objects.get(slug=self.kwargs['source'])
if src is None or src.hidden: if src is None or src.hidden:
return Entry.objects.none() return Entry.objects.none()
return Entry.objects.filter(hidden=False, source=src, created__year=dt.year, created__month=dt.month, created__day=dt.day).order_by('created') return Entry.objects.filter(
hidden=False,
source=src,
created__year=dt.year,
created__month=dt.month,
created__day=dt.day
).order_by('created')

View file

@ -1,11 +1,14 @@
from django.contrib import admin from django.contrib import admin
from .models import Element,ElementDescription from .models import Element, ElementDescription
class ElementDescriptionInline(admin.StackedInline): class ElementDescriptionInline(admin.StackedInline):
model = ElementDescription model = ElementDescription
extra = 2 extra = 2
class ElementAdmin(admin.ModelAdmin): class ElementAdmin(admin.ModelAdmin):
inlines = [ElementDescriptionInline] inlines = [ElementDescriptionInline]
admin.site.register(Element, ElementAdmin) admin.site.register(Element, ElementAdmin)

View file

@ -3,11 +3,22 @@ from django.conf import settings
from django.db import models from django.db import models
import os import os
class Element(models.Model): class Element(models.Model):
parent = models.ForeignKey('Element', on_delete=models.CASCADE, null=True, blank=True) parent = models.ForeignKey(
'Element',
on_delete=models.CASCADE,
null=True,
blank=True
)
link = models.CharField(max_length=512, blank=True) link = models.CharField(max_length=512, blank=True)
new_window = models.BooleanField(default=False) new_window = models.BooleanField(default=False)
icon = models.FilePathField(path=os.path.join(settings.BASE_DIR, 'navbar/static/icons'), match=".png", null=True, blank=True) icon = models.FilePathField(
path=os.path.join(settings.BASE_DIR, 'navbar/static/icons'),
match=".png",
null=True,
blank=True
)
weight = models.PositiveSmallIntegerField() weight = models.PositiveSmallIntegerField()
def icon_path(self): def icon_path(self):
@ -17,12 +28,16 @@ class Element(models.Model):
return Element.objects.filter(parent=self.id).order_by('weight') return Element.objects.filter(parent=self.id).order_by('weight')
def description(self): def description(self):
return ElementDescription.objects.filter(element=self.id, language=get_language()).first() return ElementDescription.objects.filter(
element=self.id,
language=get_language()
).first()
def __str__(self): def __str__(self):
desc = self.description() desc = self.description()
return desc.short_name if desc is not None else self.link return desc.short_name if desc is not None else self.link
class ElementDescription(models.Model): class ElementDescription(models.Model):
element = models.ForeignKey(Element, on_delete=models.CASCADE) element = models.ForeignKey(Element, on_delete=models.CASCADE)
language = models.CharField(max_length=10, choices=settings.LANGUAGES) language = models.CharField(max_length=10, choices=settings.LANGUAGES)

View file

@ -1,4 +1,6 @@
from django.utils.translation import get_language,gettext_lazy as _,activate as activate_lang from django.utils.translation import activate as activate_lang
from django.utils.translation import gettext_lazy as _
from django.utils.translation import get_language
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.shortcuts import render from django.shortcuts import render
@ -7,17 +9,21 @@ from django.conf import settings
from django import template from django import template
import re import re
register = template.Library() register = template.Library()
path_re = re.compile('^(/[a-z]+)/(.*)') path_re = re.compile('^(/[a-z]+)/(.*)')
def get_lang_name(lang_code): def get_lang_name(lang_code):
activate_lang(lang_code) activate_lang(lang_code)
return str([e for e in settings.LANGUAGES if e[0] == lang_code].pop()[1]) return str([e for e in settings.LANGUAGES if e[0] == lang_code].pop()[1])
def reduce_path(path): def reduce_path(path):
m = path_re.match(path) m = path_re.match(path)
return m.group(2) if m else path return m.group(2) if m else path
@register.simple_tag(takes_context=True) @register.simple_tag(takes_context=True)
def navbar(context): def navbar(context):
request = context['request'] request = context['request']

View file

@ -1,4 +1,4 @@
from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import BaseUserManager
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.core.mail import send_mail from django.core.mail import send_mail
@ -41,7 +41,9 @@ class NelUser(AbstractBaseUser, PermissionsMixin):
is_staff = models.BooleanField( is_staff = models.BooleanField(
_('staff status'), _('staff status'),
default=False, default=False,
help_text=_('Designates whether the user can log into this admin site.'), help_text=_(
'Designates whether the user can log into this admin site.'
),
) )
is_active = models.BooleanField( is_active = models.BooleanField(
_('active'), _('active'),

View file

@ -1,11 +1,14 @@
from django.contrib import admin from django.contrib import admin
from .models import Page,PageContent from .models import Page, PageContent
class PageContentInline(admin.StackedInline): class PageContentInline(admin.StackedInline):
model = PageContent model = PageContent
extra = 2 extra = 2
class PageAdmin(admin.ModelAdmin): class PageAdmin(admin.ModelAdmin):
inlines = [PageContentInline] inlines = [PageContentInline]
admin.site.register(Page, PageAdmin) admin.site.register(Page, PageAdmin)

View file

@ -9,6 +9,7 @@ class Page(models.Model):
def __str__(self): def __str__(self):
return self.slug return self.slug
class PageContent(models.Model): class PageContent(models.Model):
page = models.ForeignKey(Page, on_delete=models.CASCADE) page = models.ForeignKey(Page, on_delete=models.CASCADE)
language = models.CharField(max_length=10, choices=settings.LANGUAGES) language = models.CharField(max_length=10, choices=settings.LANGUAGES)

View file

@ -2,17 +2,21 @@ from django.utils.translation import get_language
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
from django.views import generic from django.views import generic
from django.urls import reverse from django.urls import reverse
from .models import Page,PageContent from .models import Page, PageContent
def index(request): def index(request):
default_page = Page.objects.filter(default=True).first() default_page = Page.objects.filter(default=True).first()
return HttpResponseRedirect(reverse('page', args=(default_page.slug, ))) return HttpResponseRedirect(reverse('page', args=(default_page.slug, )))
class PageView(generic.DetailView): class PageView(generic.DetailView):
model = PageContent model = PageContent
context_object_name = 'page' context_object_name = 'page'
template_name = 'pages/page.html' template_name = 'pages/page.html'
def get_object(self): def get_object(self):
return PageContent.objects.filter(language=get_language(), page__slug=self.kwargs['slug']).first() return PageContent.objects.filter(
language=get_language(),
page__slug=self.kwargs['slug']
).first()