Format com

This commit is contained in:
Pierre Brunet 2017-06-12 08:59:03 +02:00
parent 73b2c9d4c5
commit 4f4ea5dde9
5 changed files with 78 additions and 59 deletions

View File

@ -30,5 +30,3 @@ admin.site.register(Sith)
admin.site.register(News) admin.site.register(News)
admin.site.register(Weekmail) admin.site.register(Weekmail)

View File

@ -25,15 +25,14 @@
from django.shortcuts import render from django.shortcuts import render
from django.db import models, transaction from django.db import models, transaction
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse_lazy, reverse from django.core.urlresolvers import reverse
from django.conf import settings from django.conf import settings
from django.contrib.staticfiles.templatetags.staticfiles import static from django.contrib.staticfiles.templatetags.staticfiles import static
from django.core.mail import EmailMultiAlternatives from django.core.mail import EmailMultiAlternatives
from django.core.exceptions import ValidationError
from core.models import User, Preferences from core.models import User, Preferences
from club.models import Club from club.models import Club
import os
class Sith(models.Model): class Sith(models.Model):
"""A one instance class storing all the modifiable infos""" """A one instance class storing all the modifiable infos"""
@ -48,12 +47,14 @@ class Sith(models.Model):
def __str__(self): def __str__(self):
return "⛩ Sith ⛩" return "⛩ Sith ⛩"
NEWS_TYPES = [ NEWS_TYPES = [
('NOTICE', _('Notice')), ('NOTICE', _('Notice')),
('EVENT', _('Event')), ('EVENT', _('Event')),
('WEEKLY', _('Weekly')), ('WEEKLY', _('Weekly')),
('CALL', _('Call')), ('CALL', _('Call')),
] ]
class News(models.Model): class News(models.Model):
"""The news class""" """The news class"""
@ -81,6 +82,7 @@ class News(models.Model):
def __str__(self): def __str__(self):
return "%s: %s" % (self.type, self.title) return "%s: %s" % (self.type, self.title)
class NewsDate(models.Model): class NewsDate(models.Model):
""" """
A date class, useful for weekly events, or for events that just have no date A date class, useful for weekly events, or for events that just have no date
@ -95,6 +97,7 @@ class NewsDate(models.Model):
def __str__(self): def __str__(self):
return "%s: %s - %s" % (self.news.title, self.start_date, self.end_date) return "%s: %s - %s" % (self.news.title, self.start_date, self.end_date)
class Weekmail(models.Model): class Weekmail(models.Model):
""" """
The weekmail class The weekmail class
@ -113,12 +116,12 @@ class Weekmail(models.Model):
dest = [i[0] for i in Preferences.objects.filter(receive_weekmail=True).values_list('user__email')] dest = [i[0] for i in Preferences.objects.filter(receive_weekmail=True).values_list('user__email')]
with transaction.atomic(): with transaction.atomic():
email = EmailMultiAlternatives( email = EmailMultiAlternatives(
subject=self.title, subject=self.title,
body=self.render_text(), body=self.render_text(),
from_email=settings.SITH_COM_EMAIL, from_email=settings.SITH_COM_EMAIL,
to=Sith.objects.first().weekmail_destinations.split(' '), to=Sith.objects.first().weekmail_destinations.split(' '),
bcc=dest, bcc=dest,
) )
email.attach_alternative(self.render_html(), "text/html") email.attach_alternative(self.render_html(), "text/html")
email.send() email.send()
self.sent = True self.sent = True
@ -128,12 +131,12 @@ class Weekmail(models.Model):
def render_text(self): def render_text(self):
return render(None, "com/weekmail_renderer_text.jinja", context={ return render(None, "com/weekmail_renderer_text.jinja", context={
'weekmail': self, 'weekmail': self,
}).content.decode('utf-8') }).content.decode('utf-8')
def render_html(self): def render_html(self):
return render(None, "com/weekmail_renderer_html.jinja", context={ return render(None, "com/weekmail_renderer_html.jinja", context={
'weekmail': self, 'weekmail': self,
}).content.decode('utf-8') }).content.decode('utf-8')
def get_banner(self): def get_banner(self):
return "http://" + settings.SITH_URL + static("com/img/weekmail_banner.png") return "http://" + settings.SITH_URL + static("com/img/weekmail_banner.png")
@ -144,6 +147,7 @@ class Weekmail(models.Model):
def is_owned_by(self, user): def is_owned_by(self, user):
return user.is_in_group(settings.SITH_GROUP_COM_ADMIN_ID) return user.is_in_group(settings.SITH_GROUP_COM_ADMIN_ID)
class WeekmailArticle(models.Model): class WeekmailArticle(models.Model):
weekmail = models.ForeignKey(Weekmail, related_name="articles", verbose_name=_("weekmail"), null=True) weekmail = models.ForeignKey(Weekmail, related_name="articles", verbose_name=_("weekmail"), null=True)
title = models.CharField(_("title"), max_length=64) title = models.CharField(_("title"), max_length=64)

View File

@ -28,7 +28,7 @@ from django.core.urlresolvers import reverse
from django.core.management import call_command from django.core.management import call_command
from core.models import User, RealGroup from core.models import User, RealGroup
from com.models import Sith
class ComTest(TestCase): class ComTest(TestCase):
def setUp(self): def setUp(self):
@ -56,4 +56,3 @@ class ComTest(TestCase):
r = self.client.get(reverse("core:index")) r = self.client.get(reverse("core:index"))
self.assertTrue(r.status_code == 200) self.assertTrue(r.status_code == 200)
self.assertTrue("""<div id="info_box">\\n <div class="markdown"><h3>INFO: <strong>Caaaataaaapuuuulte!!!!</strong></h3>""" in str(r.content)) self.assertTrue("""<div id="info_box">\\n <div class="markdown"><h3>INFO: <strong>Caaaataaaapuuuulte!!!!</strong></h3>""" in str(r.content))

View File

@ -22,7 +22,7 @@
# #
# #
from django.conf.urls import url, include from django.conf.urls import url
from com.views import * from com.views import *

View File

@ -22,9 +22,9 @@
# #
# #
from django.shortcuts import render, redirect, get_object_or_404 from django.shortcuts import redirect, get_object_or_404
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
from django.views.generic import ListView, DetailView, RedirectView from django.views.generic import ListView, DetailView
from django.views.generic.edit import UpdateView, CreateView, DeleteView from django.views.generic.edit import UpdateView, CreateView, DeleteView
from django.views.generic.detail import SingleObjectMixin from django.views.generic.detail import SingleObjectMixin
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
@ -49,6 +49,7 @@ from club.models import Club
sith = Sith.objects.first sith = Sith.objects.first
class ComTabsMixin(TabedViewMixin): class ComTabsMixin(TabedViewMixin):
def get_tabs_title(self): def get_tabs_title(self):
return _("Communication administration") return _("Communication administration")
@ -56,32 +57,33 @@ class ComTabsMixin(TabedViewMixin):
def get_list_of_tabs(self): def get_list_of_tabs(self):
tab_list = [] tab_list = []
tab_list.append({ tab_list.append({
'url': reverse('com:weekmail'), 'url': reverse('com:weekmail'),
'slug': 'weekmail', 'slug': 'weekmail',
'name': _("Weekmail"), 'name': _("Weekmail"),
}) })
tab_list.append({ tab_list.append({
'url': reverse('com:weekmail_destinations'), 'url': reverse('com:weekmail_destinations'),
'slug': 'weekmail_destinations', 'slug': 'weekmail_destinations',
'name': _("Weekmail destinations"), 'name': _("Weekmail destinations"),
}) })
tab_list.append({ tab_list.append({
'url': reverse('com:index_edit'), 'url': reverse('com:index_edit'),
'slug': 'index', 'slug': 'index',
'name': _("Index page"), 'name': _("Index page"),
}) })
tab_list.append({ tab_list.append({
'url': reverse('com:info_edit'), 'url': reverse('com:info_edit'),
'slug': 'info', 'slug': 'info',
'name': _("Info message"), 'name': _("Info message"),
}) })
tab_list.append({ tab_list.append({
'url': reverse('com:alert_edit'), 'url': reverse('com:alert_edit'),
'slug': 'alert', 'slug': 'alert',
'name': _("Alert message"), 'name': _("Alert message"),
}) })
return tab_list return tab_list
class ComEditView(ComTabsMixin, CanEditPropMixin, UpdateView): class ComEditView(ComTabsMixin, CanEditPropMixin, UpdateView):
model = Sith model = Sith
template_name = 'core/edit.jinja' template_name = 'core/edit.jinja'
@ -89,21 +91,25 @@ class ComEditView(ComTabsMixin, CanEditPropMixin, UpdateView):
def get_object(self, queryset=None): def get_object(self, queryset=None):
return Sith.objects.first() return Sith.objects.first()
class AlertMsgEditView(ComEditView): class AlertMsgEditView(ComEditView):
fields = ['alert_msg'] fields = ['alert_msg']
current_tab = "alert" current_tab = "alert"
success_url = reverse_lazy('com:alert_edit') success_url = reverse_lazy('com:alert_edit')
class InfoMsgEditView(ComEditView): class InfoMsgEditView(ComEditView):
fields = ['info_msg'] fields = ['info_msg']
current_tab = "info" current_tab = "info"
success_url = reverse_lazy('com:info_edit') success_url = reverse_lazy('com:info_edit')
class IndexEditView(ComEditView): class IndexEditView(ComEditView):
fields = ['index_page'] fields = ['index_page']
current_tab = "index" current_tab = "index"
success_url = reverse_lazy('com:index_edit') success_url = reverse_lazy('com:index_edit')
class WeekmailDestinationEditView(ComEditView): class WeekmailDestinationEditView(ComEditView):
fields = ['weekmail_destinations'] fields = ['weekmail_destinations']
current_tab = "weekmail_destinations" current_tab = "weekmail_destinations"
@ -111,14 +117,15 @@ class WeekmailDestinationEditView(ComEditView):
# News # News
class NewsForm(forms.ModelForm): class NewsForm(forms.ModelForm):
class Meta: class Meta:
model = News model = News
fields = ['type', 'title', 'club', 'summary', 'content', 'author'] fields = ['type', 'title', 'club', 'summary', 'content', 'author']
widgets = { widgets = {
'author': forms.HiddenInput, 'author': forms.HiddenInput,
'type': forms.RadioSelect, 'type': forms.RadioSelect,
} }
start_date = forms.DateTimeField(['%Y-%m-%d %H:%M:%S'], label=_("Start date"), widget=SelectDateTime, required=False) start_date = forms.DateTimeField(['%Y-%m-%d %H:%M:%S'], label=_("Start date"), widget=SelectDateTime, required=False)
end_date = forms.DateTimeField(['%Y-%m-%d %H:%M:%S'], label=_("End date"), widget=SelectDateTime, required=False) end_date = forms.DateTimeField(['%Y-%m-%d %H:%M:%S'], label=_("End date"), widget=SelectDateTime, required=False)
until = forms.DateTimeField(['%Y-%m-%d %H:%M:%S'], label=_("Until"), widget=SelectDateTime, required=False) until = forms.DateTimeField(['%Y-%m-%d %H:%M:%S'], label=_("Until"), widget=SelectDateTime, required=False)
@ -142,19 +149,20 @@ class NewsForm(forms.ModelForm):
self.instance.dates.all().delete() self.instance.dates.all().delete()
if self.instance.type == "EVENT" or self.instance.type == "CALL": if self.instance.type == "EVENT" or self.instance.type == "CALL":
NewsDate(start_date=self.cleaned_data['start_date'], NewsDate(start_date=self.cleaned_data['start_date'],
end_date=self.cleaned_data['end_date'], end_date=self.cleaned_data['end_date'],
news=self.instance).save() news=self.instance).save()
elif self.instance.type == "WEEKLY": elif self.instance.type == "WEEKLY":
start_date = self.cleaned_data['start_date'] start_date = self.cleaned_data['start_date']
end_date = self.cleaned_data['end_date'] end_date = self.cleaned_data['end_date']
while start_date <= self.cleaned_data['until']: while start_date <= self.cleaned_data['until']:
NewsDate(start_date=start_date, NewsDate(start_date=start_date,
end_date=end_date, end_date=end_date,
news=self.instance).save() news=self.instance).save()
start_date += timedelta(days=7) start_date += timedelta(days=7)
end_date += timedelta(days=7) end_date += timedelta(days=7)
return ret return ret
class NewsEditView(CanEditMixin, UpdateView): class NewsEditView(CanEditMixin, UpdateView):
model = News model = News
form_class = NewsForm form_class = NewsForm
@ -165,15 +173,17 @@ class NewsEditView(CanEditMixin, UpdateView):
init = {} init = {}
try: try:
init['start_date'] = self.object.dates.order_by('id').first().start_date.strftime('%Y-%m-%d %H:%M:%S') init['start_date'] = self.object.dates.order_by('id').first().start_date.strftime('%Y-%m-%d %H:%M:%S')
except: pass except:
pass
try: try:
init['end_date'] = self.object.dates.order_by('id').first().end_date.strftime('%Y-%m-%d %H:%M:%S') init['end_date'] = self.object.dates.order_by('id').first().end_date.strftime('%Y-%m-%d %H:%M:%S')
except: pass except:
pass
return init return init
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
form = self.get_form() form = self.get_form()
if form.is_valid() and not 'preview' in request.POST.keys(): if form.is_valid() and 'preview' not in request.POST.keys():
return self.form_valid(form) return self.form_valid(form)
else: else:
return self.form_invalid(form) return self.form_invalid(form)
@ -192,6 +202,7 @@ class NewsEditView(CanEditMixin, UpdateView):
Notification(user=u, url=reverse("com:news_detail", kwargs={'news_id': self.object.id}), type="NEWS_MODERATION").save() Notification(user=u, url=reverse("com:news_detail", kwargs={'news_id': self.object.id}), type="NEWS_MODERATION").save()
return super(NewsEditView, self).form_valid(form) return super(NewsEditView, self).form_valid(form)
class NewsCreateView(CanCreateMixin, CreateView): class NewsCreateView(CanCreateMixin, CreateView):
model = News model = News
form_class = NewsForm form_class = NewsForm
@ -201,12 +212,13 @@ class NewsCreateView(CanCreateMixin, CreateView):
init = {'author': self.request.user} init = {'author': self.request.user}
try: try:
init['club'] = Club.objects.filter(id=self.request.GET['club']).first() init['club'] = Club.objects.filter(id=self.request.GET['club']).first()
except: pass except:
pass
return init return init
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
form = self.get_form() form = self.get_form()
if form.is_valid() and not 'preview' in request.POST.keys(): if form.is_valid() and 'preview' not in request.POST.keys():
return self.form_valid(form) return self.form_valid(form)
else: else:
self.object = form.instance self.object = form.instance
@ -224,6 +236,7 @@ class NewsCreateView(CanCreateMixin, CreateView):
Notification(user=u, url=reverse("com:news_detail", kwargs={'news_id': self.object.id}), type="NEWS_MODERATION").save() Notification(user=u, url=reverse("com:news_detail", kwargs={'news_id': self.object.id}), type="NEWS_MODERATION").save()
return super(NewsCreateView, self).form_valid(form) return super(NewsCreateView, self).form_valid(form)
class NewsModerateView(CanEditMixin, SingleObjectMixin): class NewsModerateView(CanEditMixin, SingleObjectMixin):
model = News model = News
pk_url_kwarg = 'news_id' pk_url_kwarg = 'news_id'
@ -240,11 +253,13 @@ class NewsModerateView(CanEditMixin, SingleObjectMixin):
return redirect(self.request.GET['next']) return redirect(self.request.GET['next'])
return redirect('com:news_admin_list') return redirect('com:news_admin_list')
class NewsAdminListView(CanEditMixin, ListView): class NewsAdminListView(CanEditMixin, ListView):
model = News model = News
template_name = 'com/news_admin_list.jinja' template_name = 'com/news_admin_list.jinja'
queryset = News.objects.filter(dates__end_date__gte=timezone.now()).distinct().order_by('id') queryset = News.objects.filter(dates__end_date__gte=timezone.now()).distinct().order_by('id')
class NewsListView(CanViewMixin, ListView): class NewsListView(CanViewMixin, ListView):
model = News model = News
template_name = 'com/news_list.jinja' template_name = 'com/news_list.jinja'
@ -255,6 +270,7 @@ class NewsListView(CanViewMixin, ListView):
kwargs['timedelta'] = timedelta kwargs['timedelta'] = timedelta
return kwargs return kwargs
class NewsDetailView(CanViewMixin, DetailView): class NewsDetailView(CanViewMixin, DetailView):
model = News model = News
template_name = 'com/news_detail.jinja' template_name = 'com/news_detail.jinja'
@ -262,6 +278,7 @@ class NewsDetailView(CanViewMixin, DetailView):
# Weekmail # Weekmail
class WeekmailPreviewView(ComTabsMixin, CanEditPropMixin, DetailView): class WeekmailPreviewView(ComTabsMixin, CanEditPropMixin, DetailView):
model = Weekmail model = Weekmail
template_name = 'com/weekmail_preview.jinja' template_name = 'com/weekmail_preview.jinja'
@ -274,7 +291,8 @@ class WeekmailPreviewView(ComTabsMixin, CanEditPropMixin, DetailView):
if request.POST['send'] == "validate": if request.POST['send'] == "validate":
self.object.send() self.object.send()
return HttpResponseRedirect(reverse('com:weekmail') + "?qn_weekmail_send_success") return HttpResponseRedirect(reverse('com:weekmail') + "?qn_weekmail_send_success")
except: pass except:
pass
return super(WeekmailEditView, self).get(request, *args, **kwargs) return super(WeekmailEditView, self).get(request, *args, **kwargs)
def get_object(self, queryset=None): def get_object(self, queryset=None):
@ -286,11 +304,12 @@ class WeekmailPreviewView(ComTabsMixin, CanEditPropMixin, DetailView):
kwargs['weekmail_rendered'] = self.object.render_html() kwargs['weekmail_rendered'] = self.object.render_html()
return kwargs return kwargs
class WeekmailEditView(ComTabsMixin, QuickNotifMixin, CanEditPropMixin, UpdateView): class WeekmailEditView(ComTabsMixin, QuickNotifMixin, CanEditPropMixin, UpdateView):
model = Weekmail model = Weekmail
template_name = 'com/weekmail.jinja' template_name = 'com/weekmail.jinja'
form_class = modelform_factory(Weekmail, fields=['title', 'intro', 'joke', 'protip', 'conclusion'], form_class = modelform_factory(Weekmail, fields=['title', 'intro', 'joke', 'protip', 'conclusion'],
help_texts={'title': _("Delete and save to regenerate")}) help_texts={'title': _("Delete and save to regenerate")})
success_url = reverse_lazy('com:weekmail') success_url = reverse_lazy('com:weekmail')
current_tab = "weekmail" current_tab = "weekmail"
@ -341,6 +360,7 @@ class WeekmailEditView(ComTabsMixin, QuickNotifMixin, CanEditPropMixin, UpdateVi
kwargs['orphans'] = WeekmailArticle.objects.filter(weekmail=None) kwargs['orphans'] = WeekmailArticle.objects.filter(weekmail=None)
return kwargs return kwargs
class WeekmailArticleEditView(ComTabsMixin, QuickNotifMixin, CanEditPropMixin, UpdateView): class WeekmailArticleEditView(ComTabsMixin, QuickNotifMixin, CanEditPropMixin, UpdateView):
"""Edit an article""" """Edit an article"""
model = WeekmailArticle model = WeekmailArticle
@ -351,6 +371,7 @@ class WeekmailArticleEditView(ComTabsMixin, QuickNotifMixin, CanEditPropMixin, U
quick_notif_url_arg = "qn_weekmail_article_edit" quick_notif_url_arg = "qn_weekmail_article_edit"
current_tab = "weekmail" current_tab = "weekmail"
class WeekmailArticleCreateView(QuickNotifMixin, CreateView): class WeekmailArticleCreateView(QuickNotifMixin, CreateView):
"""Post an article""" """Post an article"""
model = WeekmailArticle model = WeekmailArticle
@ -363,13 +384,14 @@ class WeekmailArticleCreateView(QuickNotifMixin, CreateView):
init = {} init = {}
try: try:
init['club'] = Club.objects.filter(id=self.request.GET['club']).first() init['club'] = Club.objects.filter(id=self.request.GET['club']).first()
except: pass except:
pass
return init return init
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
form = self.get_form() form = self.get_form()
self.object = form.instance self.object = form.instance
form.is_valid() # Valid a first time to populate club field form.is_valid() #  Valid a first time to populate club field
try: try:
m = form.instance.club.get_membership_for(request.user) m = form.instance.club.get_membership_for(request.user)
if m.role <= settings.SITH_MAXIMUM_FREE_ROLE: if m.role <= settings.SITH_MAXIMUM_FREE_ROLE:
@ -385,14 +407,10 @@ class WeekmailArticleCreateView(QuickNotifMixin, CreateView):
form.instance.author = self.request.user form.instance.author = self.request.user
return super(WeekmailArticleCreateView, self).form_valid(form) return super(WeekmailArticleCreateView, self).form_valid(form)
class WeekmailArticleDeleteView(CanEditPropMixin, DeleteView): class WeekmailArticleDeleteView(CanEditPropMixin, DeleteView):
"""Delete an article""" """Delete an article"""
model = WeekmailArticle model = WeekmailArticle
template_name = 'core/delete_confirm.jinja' template_name = 'core/delete_confirm.jinja'
success_url = reverse_lazy('com:weekmail') success_url = reverse_lazy('com:weekmail')
pk_url_kwarg = "article_id" pk_url_kwarg = "article_id"