Modèles de commentaires et de notifications #18

Merged
lstephan merged 21 commits from Aufinal/communication_models into master 2017-07-21 16:58:51 +02:00
16 changed files with 375 additions and 150 deletions

4
communication/apps.py Normal file
View file

@ -0,0 +1,4 @@
from django.apps import AppConfig
class CommunicationConfig(AppConfig):
name = 'communication'

View file

@ -0,0 +1,54 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-21 14:20
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('auth', '0008_alter_user_username_max_length'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='GroupSubscription',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('object_id', models.PositiveIntegerField()),
('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='auth.Group')),
],
options={
'verbose_name': 'souscription en groupe',
},
),
migrations.CreateModel(
name='UserSubscription',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('object_id', models.PositiveIntegerField()),
('is_unsub', models.BooleanField(default=False, verbose_name='désinscription')),
('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'souscription utilisateur',
},
),
migrations.AlterUniqueTogether(
name='usersubscription',
unique_together=set([('user', 'content_type', 'object_id')]),
),
migrations.AlterUniqueTogether(
name='groupsubscription',
unique_together=set([('group', 'content_type', 'object_id')]),
),
]

View file

64
communication/models.py Normal file
View file

@ -0,0 +1,64 @@
from django.db import models
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation
)
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
User = get_user_model()
class Subscription(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
abstract = True
class UserSubscription(Subscription):
user = models.ForeignKey(User)
is_unsub = models.BooleanField(
_("désinscription"),
default=False
)
class Meta:
verbose_name = _("souscription utilisateur")
unique_together = ("user", "content_type", "object_id")
class GroupSubscription(Subscription):
group = models.ForeignKey(Group)
class Meta:
verbose_name = _("souscription en groupe")
unique_together = ("group", "content_type", "object_id")
class SubscriptionMixin(models.Model):
user_subscriptions = GenericRelation(UserSubscription)
group_subscriptions = GenericRelation(GroupSubscription)
def get_all_subscribers(self):
subscribed_users = User.objects.filter(
usersubscription__in=self.user_subscriptions.filter(is_unsub=False)
)
subscribed_groups = Group.objects.filter(
groupsubscription__in=self.group_subscriptions.all()
)
subscribers_from_groups = User.objects.filter(
groups__in=subscribed_groups,
).exclude(
usersubscription__in=self.user_subscriptions.filter(
is_unsub=True
)
)
return subscribed_users.union(subscribers_from_groups)
class Meta:
abstract = True

58
communication/tests.py Normal file
View file

@ -0,0 +1,58 @@
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model
from django.test import TestCase
from datetime import timedelta
from django.utils import timezone
from .models import (UserSubscription, GroupSubscription)
from event.models import Event
User = get_user_model()
class SubscriptionTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.root = User.objects.create(username='root')
cls.user_true = User.objects.create(username='usertrue')
cls.user_false = User.objects.create(username='userfalse')
cls.user_group_true = User.objects.create(username='usergrouptrue')
cls.user_group_false = User.objects.create(username='usergroupfalse')
cls.group = Group.objects.create(name="TestGroup")
cls.user_group_true.groups.add(cls.group)
cls.user_group_false.groups.add(cls.group)
cls.event = Event.objects.create(
title='TestEvent',
slug='test',
created_by=cls.root,
creation_date=timezone.now(),
description="Ceci est un test",
beginning_date=timezone.now()
+ timedelta(days=30),
ending_date=timezone.now()
+ timedelta(days=31),
)
cls.groupsub = GroupSubscription.objects.create(
content_object=cls.event,
group=cls.group
)
cls.groupunsub = UserSubscription.objects.create(
content_object=cls.event,
user=cls.user_group_false,
is_unsub=True
)
cls.userunsub = UserSubscription.objects.create(
content_object=cls.event,
user=cls.user_false,
is_unsub=True
)
cls.usersub = UserSubscription.objects.create(
content_object=cls.event,
user=cls.user_true,
is_unsub=False
)
def test_all_subs(self):
self.assertSetEqual(set(self.event.get_all_subscribers()),
{self.user_true, self.user_group_true})

3
communication/views.py Normal file
View file

@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-21 20:14
# Generated by Django 1.11.3 on 2017-07-21 14:20
from __future__ import unicode_literals
from django.db import migrations, models
@ -16,25 +16,26 @@ class Migration(migrations.Migration):
operations = [
migrations.CreateModel(
name='AbstractEquipment',
name='Equipment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200, verbose_name='Nom du matériel')),
('stock', models.PositiveSmallIntegerField(verbose_name='Quantité disponible')),
('description', models.TextField(verbose_name='Description')),
('name', models.CharField(max_length=200, verbose_name='nom du matériel')),
('stock', models.PositiveSmallIntegerField(verbose_name='quantité disponible')),
('description', models.TextField(verbose_name='description')),
],
options={
'verbose_name': 'matériel abstrait',
'verbose_name_plural': 'matériels abstraits',
'verbose_name': 'matériel',
'verbose_name_plural': 'matériels',
},
),
migrations.CreateModel(
name='EquipmentAttribution',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('amount', models.PositiveSmallIntegerField(verbose_name='Quantité attribuée')),
('remarks', models.TextField(verbose_name="Remarques concernant l'attribution")),
('amount', models.PositiveSmallIntegerField(verbose_name='quantité attribuée')),
('remarks', models.TextField(verbose_name="remarques concernant l'attribution")),
('activity', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='event.Activity')),
('equipment', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='equipment.Equipment')),
],
options={
'verbose_name': 'attribution de matériel',
@ -45,51 +46,25 @@ class Migration(migrations.Migration):
name='EquipmentRemark',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('remark', models.TextField(verbose_name='Remarque sur le matériel')),
('remark', models.TextField(verbose_name='remarque sur le matériel')),
('amount', models.PositiveSmallIntegerField(verbose_name='quantité concernée')),
('is_broken', models.BooleanField()),
('is_lost', models.BooleanField()),
('equipment', models.ForeignKey(help_text='Matériel concerné par la remarque', on_delete=django.db.models.deletion.CASCADE, related_name='remarks', to='equipment.Equipment')),
],
options={
'verbose_name': 'remarque sur matériel',
'verbose_name_plural': 'remarques sur le matériel',
},
),
migrations.CreateModel(
name='Equipment',
fields=[
('abstractequipment_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='equipment.AbstractEquipment')),
],
options={
'verbose_name': 'matériel permanent',
'verbose_name_plural': 'matériels permanents',
},
bases=('equipment.abstractequipment',),
),
migrations.CreateModel(
name='TemporaryEquipment',
fields=[
('abstractequipment_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='equipment.AbstractEquipment')),
('event', models.ForeignKey(help_text='Évènement pour lequel le matériel a été loué ou emprunté ou apporté', on_delete=django.db.models.deletion.CASCADE, related_name='specific_equipment', to='event.Event')),
],
options={
'verbose_name': 'matériel temporaire',
'verbose_name_plural': 'matériels temporaires',
},
bases=('equipment.abstractequipment',),
),
migrations.AddField(
model_name='equipmentremark',
name='equipment',
field=models.ForeignKey(help_text='Matériel concerné par la remarque', on_delete=django.db.models.deletion.CASCADE, related_name='remarks', to='equipment.AbstractEquipment'),
),
migrations.AddField(
model_name='equipmentattribution',
name='equipment',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='equipment.AbstractEquipment'),
),
migrations.AddField(
model_name='abstractequipment',
model_name='equipment',
name='activities',
field=models.ManyToManyField(related_name='equipment', through='equipment.EquipmentAttribution', to='event.Activity'),
),
migrations.AddField(
model_name='equipment',
name='event',
field=models.ForeignKey(blank=True, help_text="Si spécifié, l'instance du modèle est spécifique à l'évènement en question", null=True, on_delete=django.db.models.deletion.CASCADE, to='event.Event', verbose_name='évènement'),
),
]

View file

@ -1,15 +1,16 @@
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from event.models import Event, Activity
from event.models import Activity, EventSpecificMixin
class AbstractEquipment(models.Model):
class Equipment(EventSpecificMixin, models.Model):
name = models.CharField(
_("Nom du matériel"),
_("nom du matériel"),
max_length=200,
)
stock = models.PositiveSmallIntegerField(_("Quantité disponible"))
description = models.TextField(_("Description"))
stock = models.PositiveSmallIntegerField(_("quantité disponible"))
description = models.TextField(_("description"))
activities = models.ManyToManyField(
Activity,
related_name="equipment",
@ -17,37 +18,18 @@ class AbstractEquipment(models.Model):
)
class Meta:
verbose_name = _("matériel abstrait")
verbose_name_plural = _("matériels abstraits")
verbose_name = _("matériel")
verbose_name_plural = _("matériels")
def __str__(self):
return self.name
class Equipment(AbstractEquipment):
class Meta:
verbose_name = _("matériel permanent")
verbose_name_plural = _("matériels permanents")
class TemporaryEquipment(AbstractEquipment):
event = models.ForeignKey(
Event,
related_name="specific_equipment",
help_text=_("Évènement pour lequel le matériel "
"a été loué ou emprunté ou apporté"),
)
class Meta:
verbose_name = _("matériel temporaire")
verbose_name_plural = _("matériels temporaires")
class EquipmentAttribution(models.Model):
equipment = models.ForeignKey(AbstractEquipment)
equipment = models.ForeignKey(Equipment)
activity = models.ForeignKey(Activity)
amount = models.PositiveSmallIntegerField(_("Quantité attribuée"))
remarks = models.TextField(_("Remarques concernant l'attribution"))
amount = models.PositiveSmallIntegerField(_("quantité attribuée"))
remarks = models.TextField(_("remarques concernant l'attribution"))
class Meta:
verbose_name = _("attribution de matériel")
@ -58,14 +40,21 @@ class EquipmentAttribution(models.Model):
self.amout,
self.activity.get_herited('title'))
def save(self, *args, **kwargs):
if self.equipment.event and self.equipment.event != self.activity.event:
raise ValidationError
super(EquipmentAttribution, self).save(*args, **kwargs)
class EquipmentRemark(models.Model):
remark = models.TextField(_("Remarque sur le matériel"))
remark = models.TextField(_("remarque sur le matériel"))
equipment = models.ForeignKey(
AbstractEquipment,
Equipment,
related_name="remarks",
help_text=_("Matériel concerné par la remarque"),
)
amount = models.PositiveSmallIntegerField(_("quantité concernée"))
is_broken = models.BooleanField()
is_lost = models.BooleanField()

View file

@ -44,6 +44,7 @@ BASE_DIR = os.path.dirname(
INSTALLED_APPS = [
'communication.apps.CommunicationConfig',
'equipment.apps.EquipmentConfig',
'event.apps.EventConfig',
'users.apps.UsersConfig',

View file

@ -12,7 +12,7 @@ urlpatterns = [
url(r'^', include('shared.urls')),
]
if settings.DEBUG:
if 'debug_toolbar' in settings.INSTALLED_APPS:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-21 20:14
# Generated by Django 1.11.3 on 2017-07-21 14:20
from __future__ import unicode_literals
from django.conf import settings
@ -17,13 +17,32 @@ class Migration(migrations.Migration):
]
operations = [
migrations.CreateModel(
name='Activity',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(blank=True, max_length=200, null=True, verbose_name="nom de l'activité")),
('is_public', models.NullBooleanField()),
('has_perm', models.NullBooleanField()),
('min_perm', models.PositiveSmallIntegerField(blank=True, null=True, verbose_name='nombre minimum de permanents')),
('max_perm', models.PositiveSmallIntegerField(blank=True, null=True, verbose_name='nombre maximum de permanents')),
('description', models.TextField(blank=True, help_text='Public, Visible par tout le monde.', null=True, verbose_name='description')),
('remarks', models.TextField(blank=True, help_text='Visible uniquement par les organisateurs', null=True, verbose_name='remarques')),
('beginning', models.DateTimeField(verbose_name='heure de début')),
('end', models.DateTimeField(verbose_name='heure de fin')),
],
options={
'verbose_name': 'activité',
'verbose_name_plural': 'activités',
},
),
migrations.CreateModel(
name='ActivityTag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200, verbose_name='Nom du tag')),
('name', models.CharField(max_length=200, verbose_name='nom du tag')),
('is_public', models.BooleanField(help_text="Sert à faire une distinction dans l'affichage selon que cela soit destiné au public ou à l'équipe organisatrice")),
('color', models.CharField(help_text='Rentrer une couleur en hexadécimal', max_length=7, validators=[django.core.validators.RegexValidator(message="La chaîne de caractère rentrée n'est pasune couleur en hexadécimal.", regex='^#(?:[0-9a-fA-F]{3}){1,2}$')], verbose_name='Couleur')),
('color', models.CharField(help_text='Rentrer une couleur en hexadécimal', max_length=7, validators=[django.core.validators.RegexValidator(message="La chaîne de caractère rentrée n'est pas une couleur en hexadécimal.", regex='^#(?:[0-9a-fA-F]{3}){1,2}$')], verbose_name='couleur')),
],
options={
'verbose_name': 'tag',
@ -34,13 +53,13 @@ class Migration(migrations.Migration):
name='ActivityTemplate',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(blank=True, max_length=200, null=True, verbose_name="Nom de l'activité")),
('title', models.CharField(blank=True, max_length=200, null=True, verbose_name="nom de l'activité")),
('is_public', models.NullBooleanField()),
('has_perm', models.NullBooleanField()),
('min_perm', models.PositiveSmallIntegerField(blank=True, null=True, verbose_name='Nombre minimum de permanents')),
('max_perm', models.PositiveSmallIntegerField(blank=True, null=True, verbose_name='Nombre maximum de permanents')),
('description', models.TextField(blank=True, help_text='Public, Visible par tout le monde.', null=True, verbose_name='Description')),
('remarks', models.TextField(blank=True, help_text='Visible uniquement par les organisateurs', null=True, verbose_name='Remarques')),
('min_perm', models.PositiveSmallIntegerField(blank=True, null=True, verbose_name='nombre minimum de permanents')),
('max_perm', models.PositiveSmallIntegerField(blank=True, null=True, verbose_name='nombre maximum de permanents')),
('description', models.TextField(blank=True, help_text='Public, Visible par tout le monde.', null=True, verbose_name='description')),
('remarks', models.TextField(blank=True, help_text='Visible uniquement par les organisateurs', null=True, verbose_name='remarques')),
],
options={
'verbose_name': 'template activité',
@ -50,12 +69,13 @@ class Migration(migrations.Migration):
migrations.CreateModel(
name='Event',
fields=[
('title', models.CharField(max_length=200, verbose_name="Nom de l'évènement")),
('slug', models.SlugField(help_text="Seulement des lettres, des chiffres oules caractères '_' ou '-'.", primary_key=True, serialize=False, unique=True, verbose_name='Identificateur')),
('creation_date', models.DateTimeField(auto_now_add=True, verbose_name='Date de création')),
('description', models.TextField(verbose_name='Description')),
('beginning_date', models.DateTimeField(verbose_name='Date de début')),
('ending_date', models.DateTimeField(verbose_name='Date de fin')),
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200, verbose_name="nom de l'évènement")),
('slug', models.SlugField(help_text="Seulement des lettres, des chiffres oules caractères '_' ou '-'.", unique=True, verbose_name='identificateur')),
('creation_date', models.DateTimeField(auto_now_add=True, verbose_name='date de création')),
('description', models.TextField(verbose_name='description')),
('beginning_date', models.DateTimeField(verbose_name='date de début')),
('ending_date', models.DateTimeField(verbose_name='date de fin')),
('created_by', models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='created_events', to=settings.AUTH_USER_MODEL)),
],
options={
@ -67,48 +87,58 @@ class Migration(migrations.Migration):
name='Place',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200, verbose_name='Nom du lieu')),
('name', models.CharField(max_length=200, verbose_name='nom du lieu')),
('description', models.TextField(blank=True)),
('event', models.ForeignKey(blank=True, help_text="Si spécifié, l'instance du modèle est spécifique à l'évènement en question", null=True, on_delete=django.db.models.deletion.CASCADE, to='event.Event', verbose_name='évènement')),
],
options={
'verbose_name': 'lieu',
'verbose_name_plural': 'lieux',
},
),
migrations.CreateModel(
name='Activity',
fields=[
('activitytemplate_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='event.ActivityTemplate')),
],
options={
'verbose_name': 'activité',
'verbose_name_plural': 'activités',
},
bases=('event.activitytemplate',),
),
migrations.AddField(
model_name='activitytemplate',
name='event',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='activities', to='event.Event'),
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='event.Event'),
),
migrations.AddField(
model_name='activitytemplate',
name='place',
field=models.ManyToManyField(blank=True, related_name='activities', to='event.Place'),
field=models.ManyToManyField(blank=True, to='event.Place'),
),
migrations.AddField(
model_name='activitytemplate',
name='tags',
field=models.ManyToManyField(blank=True, related_name='activities', to='event.ActivityTag'),
field=models.ManyToManyField(blank=True, to='event.ActivityTag'),
),
migrations.AddField(
model_name='activitytag',
name='event',
field=models.ForeignKey(blank=True, help_text="Si spécifié, l'instance du modèle est spécifique à l'évènement en question", null=True, on_delete=django.db.models.deletion.CASCADE, to='event.Event', verbose_name='évènement'),
),
migrations.AddField(
model_name='activity',
name='event',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='event.Event'),
),
migrations.AddField(
model_name='activity',
name='parent',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='children', to='event.ActivityTemplate'),
),
migrations.AddField(
model_name='activity',
name='place',
field=models.ManyToManyField(blank=True, to='event.Place'),
),
migrations.AddField(
model_name='activity',
name='staff',
field=models.ManyToManyField(blank=True, related_name='in_perm_activities', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='activity',
name='tags',
field=models.ManyToManyField(blank=True, to='event.ActivityTag'),
),
]

View file

@ -3,17 +3,17 @@ from django.utils.translation import ugettext_lazy as _
from django.core.validators import RegexValidator
from django.core.exceptions import FieldError
from django.db import models
from communication.models import SubscriptionMixin
class Event(models.Model):
class Event(SubscriptionMixin, models.Model):
title = models.CharField(
_("Nom de l'évènement"),
_("nom de l'évènement"),
max_length=200,
)
slug = models.SlugField(
_('Identificateur'),
_('identificateur'),
unique=True,
primary_key=True,
help_text=_("Seulement des lettres, des chiffres ou"
"les caractères '_' ou '-'."),
)
@ -23,12 +23,12 @@ class Event(models.Model):
editable=False,
)
creation_date = models.DateTimeField(
_('Date de création'),
_('date de création'),
auto_now_add=True,
)
description = models.TextField(_('Description'))
beginning_date = models.DateTimeField(_('Date de début'))
ending_date = models.DateTimeField(_('Date de fin'))
description = models.TextField(_('description'))
beginning_date = models.DateTimeField(_('date de début'))
ending_date = models.DateTimeField(_('date de fin'))
class Meta:
verbose_name = _("évènement")
@ -38,9 +38,26 @@ class Event(models.Model):
return self.title
class Place(models.Model):
class EventSpecificMixin(models.Model):
"""Mixin allowing for event-specific models instances
or not (depending on whether the event field is null)"""
event = models.ForeignKey(
'event.Event',
verbose_name=_("évènement"),
help_text=_("Si spécifié, l'instance du modèle "
"est spécifique à l'évènement en question"),
blank=True,
null=True
)
class Meta:
abstract = True
class Place(EventSpecificMixin, models.Model):
name = models.CharField(
_("Nom du lieu"),
_("nom du lieu"),
max_length=200,
)
description = models.TextField(blank=True)
@ -53,9 +70,9 @@ class Place(models.Model):
return self.name
class ActivityTag(models.Model):
class ActivityTag(EventSpecificMixin, models.Model):
name = models.CharField(
_("Nom du tag"),
_("nom du tag"),
max_length=200,
)
is_public = models.BooleanField(
@ -70,7 +87,7 @@ class ActivityTag(models.Model):
" une couleur en hexadécimal."),
)
color = models.CharField(
_('Couleur'),
_('couleur'),
max_length=7,
validators=[color_regex],
help_text=_("Rentrer une couleur en hexadécimal"),
@ -84,20 +101,15 @@ class ActivityTag(models.Model):
return self.name
class ActivityTemplate(models.Model):
class AbstractActivityTemplate(SubscriptionMixin, models.Model):
title = models.CharField(
_("Nom de l'activité"),
_("nom de l'activité"),
max_length=200,
blank=True,
null=True,
)
# FIXME: voir comment on traite l'héritage de `event`
event = models.ForeignKey(
Event,
related_name="activities",
blank=True,
null=True,
)
event = models.ForeignKey(Event)
is_public = models.NullBooleanField(
blank=True,
)
@ -105,38 +117,41 @@ class ActivityTemplate(models.Model):
blank=True,
)
min_perm = models.PositiveSmallIntegerField(
_('Nombre minimum de permanents'),
_('nombre minimum de permanents'),
blank=True,
null=True,
)
max_perm = models.PositiveSmallIntegerField(
_('Nombre maximum de permanents'),
_('nombre maximum de permanents'),
blank=True,
null=True,
)
description = models.TextField(
_('Description'),
_('description'),
help_text=_("Public, Visible par tout le monde."),
blank=True,
null=True,
)
remarks = models.TextField(
_('Remarques'),
_('remarques'),
help_text=_("Visible uniquement par les organisateurs"),
blank=True,
null=True,
)
tags = models.ManyToManyField(
ActivityTag,
related_name="activities",
blank=True,
)
place = models.ManyToManyField(
Place,
related_name="activities",
blank=True,
)
class Meta:
abstract = True
class ActivityTemplate(AbstractActivityTemplate):
class Meta:
verbose_name = _("template activité")
verbose_name_plural = _("templates activité")
@ -145,7 +160,7 @@ class ActivityTemplate(models.Model):
return self.title
class Activity(ActivityTemplate):
class Activity(AbstractActivityTemplate):
parent = models.ForeignKey(
ActivityTemplate,
related_name="children",
@ -156,20 +171,26 @@ class Activity(ActivityTemplate):
blank=True,
)
beginning = models.DateTimeField(_("heure de début"))
end = models.DateTimeField(_("heure de fin"))
def get_herited(self, attrname):
attr = super(Activity, self).__getattribute__(attrname)
if attrname in {"parent", "staff", "equipment"}:
inherited_fields = [f.name for f in ActivityTemplate._meta.get_fields()]
m2m_fields = [f.name for f in ActivityTemplate._meta.get_fields()
if f.many_to_many]
attr = getattr(self, attrname)
if attrname not in inherited_fields:
raise FieldError(
_("%(attrname)s n'est pas un champ héritable"),
params={'attrname': attrname},
)
elif (attrname == 'place' or attrname == 'tags'):
elif attrname in m2m_fields:
if attr.exists():
return attr
else:
return self.parent.__getattribute__(attrname)
return getattr(self.parent, attrname)
elif attr is None:
return self.parent.__getattribute__(attrname)
return getattr(self.parent, attrname)
else:
return attr

View file

@ -1,4 +1,4 @@
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.test import TestCase
from datetime import timedelta
@ -6,6 +6,8 @@ from django.utils import timezone
from .models import Event, ActivityTemplate, Activity, Place, \
ActivityTag
User = get_user_model()
class ActivityInheritanceTest(TestCase):
@classmethod
@ -41,54 +43,60 @@ class ActivityInheritanceTest(TestCase):
)
def setUp(self):
self.template_act = ActivityTemplate.objects.create()
self.template_act = ActivityTemplate.objects.create(event=self.event)
self.real_act = Activity.objects.create(
parent=self.template_act,
event=self.event,
beginning=timezone.now()
+ timedelta(days=30),
end=timezone.now()
+ timedelta(days=30)
+ timedelta(hours=2),
)
def test_inherites_title(self):
def test_inherits_title(self):
self.template_act.title = "parent"
self.assertEqual(self.real_act.get_herited('title'), "parent")
self.real_act.title = "enfant"
self.assertEqual(self.real_act.get_herited('title'), "enfant")
def test_inherites_description(self):
def test_inherits_description(self):
self.template_act.description = "parent"
self.assertEqual(self.real_act.get_herited('description'), "parent")
self.real_act.description = "enfant"
self.assertEqual(self.real_act.get_herited('description'), "enfant")
def test_inherites_remarks(self):
def test_inherits_remarks(self):
self.template_act.remarks = "parent"
self.assertEqual(self.real_act.get_herited('remarks'), "parent")
self.real_act.remarks = "enfant"
self.assertEqual(self.real_act.get_herited('remarks'), "enfant")
def test_inherites_is_public(self):
def test_inherits_is_public(self):
self.template_act.is_public = True
self.assertEqual(self.real_act.get_herited('is_public'), True)
self.real_act.is_public = False
self.assertEqual(self.real_act.get_herited('is_public'), False)
def test_inherites_has_perm(self):
def test_inherits_has_perm(self):
self.template_act.has_perm = True
self.assertEqual(self.real_act.get_herited('has_perm'), True)
self.real_act.has_perm = False
self.assertEqual(self.real_act.get_herited('has_perm'), False)
def test_inherites_min_perm(self):
def test_inherits_min_perm(self):
self.template_act.min_perm = 42
self.assertEqual(self.real_act.get_herited('min_perm'), 42)
self.real_act.min_perm = 1
self.assertEqual(self.real_act.get_herited('min_perm'), 1)
def test_inherites_max_perm(self):
def test_inherits_max_perm(self):
self.template_act.max_perm = 42
self.assertEqual(self.real_act.get_herited('max_perm'), 42)
self.real_act.max_perm = 1
self.assertEqual(self.real_act.get_herited('max_perm'), 1)
def test_inherites_place(self):
def test_inherits_place(self):
self.template_act.place.add(self.loge)
self.assertEqual(
self.real_act.get_herited('place').get(),
@ -100,7 +108,7 @@ class ActivityInheritanceTest(TestCase):
self.aqua
)
def test_inherites_tags(self):
def test_inherits_tags(self):
self.template_act.tags.add(self.tag_foo)
self.assertEqual(
self.real_act.get_herited('tags').get(),

View file

@ -5,6 +5,8 @@ Pillow
channels
django-bootstrap-form==3.2.1
django-widget-tweaks
django-notifications
django-contrib-comments
# Production specific
daphne

View file

@ -1,3 +1,19 @@
from django.db import models
from django.utils.translation import ugettext_lazy as _
# Create your models here.
class EventSpecificMixin(models.Model):
"""Mixin allowing for event-specific models instances
or not (depending on whether the event field is null)"""
event = models.ForeignKey(
'event.Event',
verbose_name=_("évènement"),
help_text=_("Si spécifié, l'instance du modèle"
"est spécifique à l'évènement en question"),
blank=True,
null=True
)
class Meta:
abstract = True