isonzeinterndronken/dronken/views.py

102 lines
2.8 KiB
Python

import lxml.html
from django import forms
from django.http import Http404, HttpResponse
from django.urls import reverse_lazy
from django.views import View
from django.views.generic import ListView, UpdateView
import anybadge
from dronken.models import City, Association
class CityList(ListView):
template_name = 'cities.html'
model = City
ordering = ['name']
class AssociationList(ListView):
template_name = 'associations.html'
model = Association
city = None
ordering = ['short_name']
def get_queryset(self):
self.city = City.objects.get(slug=self.kwargs['city'])
return Association.objects.filter(city=self.city)
def get_context_data(self, *args, **kwargs):
context = super(AssociationList, self).get_context_data(*args, **kwargs)
context['city'] = self.city
return context
class DrunkUpdateForm(forms.ModelForm):
state = forms.CharField(
widget=forms.Select(choices=Association.STATES),
)
class Meta:
model = Association
fields = ['state']
def __init__(self, *args, **kwargs):
super(DrunkUpdateForm, self).__init__(*args, **kwargs)
self.fields['state'] = forms.ChoiceField(
choices=list(Association.STATES) + [(o.value, o.name) for o in self.instance.extra_states.all()]
)
def clean(self):
print(self.instance.state)
return super(DrunkUpdateForm, self).clean()
class AssociationDetail(UpdateView):
template_name = 'association.html'
model = Association
form_class = DrunkUpdateForm
def get_success_url(self):
return reverse_lazy('dronken:association_list', kwargs={'city': self.get_object().city.slug})
class AssociationBadgeView(View):
def get(self, *args, **kwargs):
city = kwargs['city']
slug = kwargs['slug']
try:
city_obj = City.objects.get(slug=city)
except City.DoesNotExist:
raise Http404
try:
association = Association.objects.get(city=city_obj, slug=slug)
except Association.DoesNotExist:
raise Http404
image = self.generate_badge(association)
return HttpResponse(image, content_type="image/svg+xml")
STATE_TO_COLOR = {
'nuchter': 'lightgrey',
'dronken': 'green',
'brak': 'yellowgreen',
}
def generate_badge(self, association):
color = AssociationBadgeView.STATE_TO_COLOR.get(association.state, 'yellow')
if not association.has_intern:
color = 'lightgrey'
badge = anybadge.Badge(lxml.html.fromstring(association.short_name).text_content(),
association.get_state_display(),
default_color=color)
return badge.badge_svg_text