Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
.PHONY: init
.PHONY: init psql

init:
. ${NVM_DIR}/nvm.sh && nvm use
Expand All @@ -9,6 +9,9 @@ init:
run_db:
docker compose -f docker-compose-dev.yml up db -d

psql:
docker compose -f docker-compose-dev.yml exec db psql -U postgres -d pycontw2016

run_local: init run_db
export DATABASE_URL=postgresql://postgres:secretpostgres@127.0.0.1:5432/pycontw2016
poetry run python src/manage.py runserver 0.0.0.0:8000
Expand All @@ -24,4 +27,4 @@ remove_dev:
docker compose -f docker-compose-dev.yml down

shell_dev:
docker compose -f docker-compose-dev.yml exec -it pycontw /bin/sh
docker compose -f docker-compose-dev.yml exec -it pycontw /bin/bash
5 changes: 5 additions & 0 deletions docker-compose-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ services:
- POSTGRES_PASSWORD=secretpostgres
ports:
- ${COMPOSE_DB_PORT:-5432}:5432
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: "pg_isready"
start_period: 5s
Expand All @@ -33,3 +35,6 @@ services:
- DATABASE_URL=postgres://postgres:secretpostgres@db:5432/pycontw2016
command: "python3 manage.py runserver 0.0.0.0:8000"
working_dir: /usr/local/app/src

volumes:
postgres_data:
11 changes: 9 additions & 2 deletions document/deploy_docker_dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,19 @@

# Containerized Development Environment

1. Simply run the following command to start containerized services, this will run both the database and django service for you:
1. Create `local.env` file:
```
cp src/pycontw2016/settings/local.sample.env \
src/pycontw2016/settings/local.env
# Replace {{ secret_key }} with the instructions in `local.sample.env`
```

2. Simply run the following command to start containerized services, this will run both the database and django service for you:
```
make run_dev
```

2. If the services are up and running in the first time, you may need to run the following in `pycontw` service in docker shell.
3. If the services are up and running in the first time, you may need to run the following in `pycontw` service in docker shell.

To get into the docker shell for `pycontw`

Expand Down
109 changes: 109 additions & 0 deletions src/events/fields.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
from django import forms
from django.core import exceptions
from django.db import models
from django.utils.html import format_html
from django.utils.text import capfirst
from django.utils.translation import gettext_lazy as _

CUSTOM_LOCATION = '__custom__'


class EventLocationWidget(forms.MultiWidget):

def __init__(self, choices, max_length, attrs=None):
widgets = [
forms.Select(
choices=choices,
attrs={'class': 'event-location-mode'},
),
forms.TextInput(attrs={
'class': 'vTextField event-location-custom',
'maxlength': max_length,
'placeholder': _('custom location'),
}),
]
super().__init__(widgets, attrs)

def render(self, name, value, attrs=None, renderer=None):
rendered_widget = super().render(name, value, attrs, renderer)
return format_html(
'<div class="related-widget-wrapper event-location-widget">{}</div>',
rendered_widget,
)

def decompress(self, value):
location_choices = dict(self.widgets[0].choices)
if value in location_choices:
return [value, '']
if value:
return [CUSTOM_LOCATION, value]
return ['', '']

class Media:
css = {'all': ('events/admin/event_location.css',)}
js = ('events/admin/event_location.js',)


class EventLocationField(forms.MultiValueField):

def __init__(self, choices, max_length, **kwargs):
choices = [
('', '---------'),
*choices,
(CUSTOM_LOCATION, _('Custom…')),
]
fields = [
forms.ChoiceField(choices=choices, required=False),
forms.CharField(max_length=max_length, required=False),
]
kwargs.setdefault('label', _('location'))
kwargs.setdefault('required', False)
super().__init__(
fields=fields,
require_all_fields=False,
widget=EventLocationWidget(choices, max_length),
**kwargs,
)

def compress(self, data_list):
if not data_list:
return None

location_mode, custom_location = data_list
if location_mode == CUSTOM_LOCATION:
if not custom_location:
raise exceptions.ValidationError(_('Enter a custom location.'))
return custom_location
return location_mode or None


class EventLocationModelField(models.CharField):

def formfield(self, **kwargs):
defaults = {
'choices': self.choices,
'max_length': self.max_length,
'label': capfirst(self.verbose_name),
'required': not self.blank,
'help_text': self.help_text,
}
defaults.update(kwargs)
return EventLocationField(**defaults)

def validate(self, value, model_instance):
if not self.editable:
return
if value is None and not self.null:
raise exceptions.ValidationError(
self.error_messages['null'],
code='null',
)
if not self.blank and value in self.empty_values:
raise exceptions.ValidationError(
self.error_messages['blank'],
code='blank',
)

def deconstruct(self):
name, _, args, kwargs = super().deconstruct()
return name, 'django.db.models.CharField', args, kwargs
4 changes: 3 additions & 1 deletion src/events/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
from proposals.models import PrimarySpeaker, TalkProposal, TutorialProposal
from sponsors.models import Sponsor

from .fields import EventLocationModelField

MIDNIGHT_TIME = datetime.time(tzinfo=pytz.timezone('Asia/Taipei'))

EVENT_DATETIME_START_END = (
Expand Down Expand Up @@ -142,7 +144,7 @@ class BaseEvent(ConferenceRelated):
(Location.TUTORIAL, _('Tutorial')),
(Location.YI_PS, _('Young Inspire / Poster Session')),
]
location = models.CharField(
location = EventLocationModelField(
max_length=12,
choices=LOCATION_CHOICES,
blank=True,
Expand Down
121 changes: 121 additions & 0 deletions src/events/tests/test_custom_event_locations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import datetime

import pytest
from django.conf import settings
from django.utils import timezone

from events.fields import CUSTOM_LOCATION
from events.forms import CustomEventForm
from events.models import CustomEvent, Location, Time


def make_time(date, hour):
value = timezone.make_aware(datetime.datetime.combine(date, datetime.time(hour)))
return Time.all_objects.create(value=value)


@pytest.mark.django_db
def test_custom_event_form_saves_predefined_location():
form = CustomEventForm(data={
'conference': settings.CONFERENCE_DEFAULT_SLUG,
'title': 'Scheduled event',
'location_0': Location.R0,
'description': '',
'link_path': '',
})

assert form.is_valid(), form.errors
event = form.save()
assert event.location == Location.R0


@pytest.mark.django_db
def test_custom_event_form_saves_custom_location():
form = CustomEventForm(data={
'conference': settings.CONFERENCE_DEFAULT_SLUG,
'title': 'Off-site event',
'location_0': CUSTOM_LOCATION,
'location_1': 'lobby',
'description': '',
'link_path': '',
})

assert form.is_valid(), form.errors
event = form.save()
assert event.location == 'lobby'


def test_custom_event_form_initializes_custom_location():
form = CustomEventForm(instance=CustomEvent(location='lobby'))

assert form.fields['location'].widget.decompress(form.initial['location']) == [
CUSTOM_LOCATION,
'lobby',
]


def test_custom_event_form_requires_custom_location():
form = CustomEventForm(data={
'conference': settings.CONFERENCE_DEFAULT_SLUG,
'title': 'Off-site event',
'location_0': CUSTOM_LOCATION,
'location_1': '',
'description': '',
'link_path': '',
})

assert not form.is_valid()
assert form.errors['location'] == ['Enter a custom location.']


def test_custom_event_form_limits_custom_location_to_twelve_characters():
form = CustomEventForm(data={
'conference': settings.CONFERENCE_DEFAULT_SLUG,
'title': 'Off-site event',
'location_0': CUSTOM_LOCATION,
'location_1': 'x' * 13,
'description': '',
'link_path': '',
})

assert not form.is_valid()
assert 'location' in form.errors


@pytest.mark.django_db
def test_schedule_api_treats_custom_location_as_one_room(api_client):
dates = list(settings.EVENTS_DAY_NAMES)
for index, date in enumerate(dates):
CustomEvent.objects.create(
title=f'Event {index}',
begin_time=make_time(date, 9),
end_time=make_time(date, 10),
location='lobby' if index == 0 else Location.R2,
)

response = api_client.get('/api/events/schedule/')

assert response.status_code == 200
first_day = response.json()['data'][0]
assert 'lobby' in first_day['rooms']
assert len(first_day['slots']['lobby']) == 1


@pytest.mark.django_db
def test_ccip_treats_custom_location_as_one_room(client):
date = next(iter(settings.EVENTS_DAY_NAMES))
event = CustomEvent.objects.create(
title='Off-site event',
begin_time=make_time(date, 9),
end_time=make_time(date, 10),
location='lobby',
)

response = client.get('/ccip/')

assert response.status_code == 200
data = response.json()
session = next(item for item in data['sessions'] if item['id'] == f'event-{event.pk}')
assert session['room'] == 'lobby'
assert session['broadcast'] == []
assert 'lobby' in {room['id'] for room in data['rooms']}
Loading