Fix some ugly lines

This commit is contained in:
Antoine Bartuccio 2017-06-07 19:16:55 +02:00
parent 41a9bf9953
commit b6a68fa090
2 changed files with 60 additions and 109 deletions

View File

@ -11,8 +11,7 @@ class Election(models.Model):
""" """
title = models.CharField(_('title'), max_length=255) title = models.CharField(_('title'), max_length=255)
description = models.TextField(_('description'), null=True, blank=True) description = models.TextField(_('description'), null=True, blank=True)
start_candidature = models.DateTimeField( start_candidature = models.DateTimeField(_('start candidature'), blank=False)
_('start candidature'), blank=False)
end_candidature = models.DateTimeField(_('end candidature'), blank=False) end_candidature = models.DateTimeField(_('end candidature'), blank=False)
start_date = models.DateTimeField(_('start date'), blank=False) start_date = models.DateTimeField(_('start date'), blank=False)
end_date = models.DateTimeField(_('end date'), blank=False) end_date = models.DateTimeField(_('end date'), blank=False)
@ -20,17 +19,20 @@ class Election(models.Model):
edit_groups = models.ManyToManyField( edit_groups = models.ManyToManyField(
Group, related_name="editable_elections", Group, related_name="editable_elections",
verbose_name=_("edit groups"), blank=True) verbose_name=_("edit groups"), blank=True)
view_groups = models.ManyToManyField( view_groups = models.ManyToManyField(
Group, related_name="viewable_elections", Group, related_name="viewable_elections",
verbose_name=_("view groups"), blank=True) verbose_name=_("view groups"), blank=True)
vote_groups = models.ManyToManyField( vote_groups = models.ManyToManyField(
Group, related_name="votable_elections", Group, related_name="votable_elections",
verbose_name=_("vote groups"), blank=True) verbose_name=_("vote groups"), blank=True)
candidature_groups = models.ManyToManyField( candidature_groups = models.ManyToManyField(
Group, related_name="candidate_elections", Group, related_name="candidate_elections",
verbose_name=_("candidature groups"), blank=True) verbose_name=_("candidature groups"), blank=True)
voters = models.ManyToManyField(User, verbose_name=(
'voters'), related_name='voted_elections') voters = models.ManyToManyField(User, verbose_name=('voters'), related_name='voted_elections')
archived = models.BooleanField(_("archived"), default=False) archived = models.BooleanField(_("archived"), default=False)
def __str__(self): def __str__(self):
@ -48,8 +50,7 @@ class Election(models.Model):
@property @property
def is_candidature_active(self): def is_candidature_active(self):
now = timezone.now() now = timezone.now()
return bool(now <= self.end_candidature and return bool(now <= self.end_candidature and now >= self.start_candidature)
now >= self.start_candidature)
@property @property
def is_vote_editable(self): def is_vote_editable(self):
@ -87,8 +88,7 @@ class Role(models.Model):
""" """
This class allows to create a new role avaliable for a candidature This class allows to create a new role avaliable for a candidature
""" """
election = models.ForeignKey( election = models.ForeignKey(Election, related_name='roles', verbose_name=_("election"))
Election, related_name='roles', verbose_name=_("election"))
title = models.CharField(_('title'), max_length=255) title = models.CharField(_('title'), max_length=255)
description = models.TextField(_('description'), null=True, blank=True) description = models.TextField(_('description'), null=True, blank=True)
max_choice = models.IntegerField(_('max choice'), default=1) max_choice = models.IntegerField(_('max choice'), default=1)
@ -99,22 +99,18 @@ class Role(models.Model):
non_blank = 0 non_blank = 0
for candidature in self.candidatures.all(): for candidature in self.candidatures.all():
cand_results = {} cand_results = {}
cand_results['vote'] = self.votes.filter( cand_results['vote'] = self.votes.filter(candidature=candidature).count()
candidature=candidature).count()
if total_vote == 0: if total_vote == 0:
cand_results['percent'] = 0 cand_results['percent'] = 0
else: else:
cand_results['percent'] = cand_results[ cand_results['percent'] = cand_results['vote'] * 100 / total_vote
'vote'] * 100 / total_vote
non_blank += cand_results['vote'] non_blank += cand_results['vote']
results[candidature.user.username] = cand_results results[candidature.user.username] = cand_results
results['total vote'] = total_vote results['total vote'] = total_vote
if total_vote == 0: if total_vote == 0:
results['blank vote'] = {'vote': 0, 'percent': 0} results['blank vote'] = {'vote': 0, 'percent': 0}
else: else:
results['blank vote'] = {'vote': total_vote - non_blank, results['blank vote'] = {'vote': total_vote - non_blank, 'percent': (total_vote - non_blank) * 100 / total_vote}
'percent': (total_vote -
non_blank) * 100 / total_vote}
return results return results
@property @property
@ -130,8 +126,7 @@ class ElectionList(models.Model):
To allow per list vote To allow per list vote
""" """
title = models.CharField(_('title'), max_length=255) title = models.CharField(_('title'), max_length=255)
election = models.ForeignKey( election = models.ForeignKey(Election, related_name='election_lists', verbose_name=_("election"))
Election, related_name='election_lists', verbose_name=_("election"))
def __str__(self): def __str__(self):
return self.title return self.title
@ -141,14 +136,10 @@ class Candidature(models.Model):
""" """
This class is a component of responsability This class is a component of responsability
""" """
role = models.ForeignKey( role = models.ForeignKey(Role, related_name='candidatures', verbose_name=_("role"))
Role, related_name='candidatures', verbose_name=_("role")) user = models.ForeignKey(User, verbose_name=_('user'), related_name='candidates', blank=True)
user = models.ForeignKey(User, verbose_name=_(
'user'), related_name='candidates', blank=True)
program = models.TextField(_('description'), null=True, blank=True) program = models.TextField(_('description'), null=True, blank=True)
election_list = models.ForeignKey( election_list = models.ForeignKey(ElectionList, related_name='candidatures', verbose_name=_('election list'))
ElectionList, related_name='candidatures',
verbose_name=_('election list'))
def can_be_edited_by(self, user): def can_be_edited_by(self, user):
return (user == self.user) or user.can_edit(self.role.election) return (user == self.user) or user.can_edit(self.role.election)
@ -161,10 +152,8 @@ class Vote(models.Model):
""" """
This class allows to vote for candidates This class allows to vote for candidates
""" """
role = models.ForeignKey( role = models.ForeignKey(Role, related_name='votes', verbose_name=_("role"))
Role, related_name='votes', verbose_name=_("role")) candidature = models.ManyToManyField(Candidature, related_name='votes', verbose_name=_("candidature"))
candidature = models.ManyToManyField(
Candidature, related_name='votes', verbose_name=_("candidature"))
def __str__(self): def __str__(self):
return "Vote" return "Vote"

View File

@ -29,8 +29,7 @@ class LimitedCheckboxField(forms.ModelMultipleChoiceField):
label=None, initial=None, help_text='', *args, **kwargs): label=None, initial=None, help_text='', *args, **kwargs):
self.max_choice = max_choice self.max_choice = max_choice
widget = forms.CheckboxSelectMultiple() widget = forms.CheckboxSelectMultiple()
super(LimitedCheckboxField, self).__init__(queryset, super(LimitedCheckboxField, self).__init__(queryset, None, required,
None, required,
widget, label, widget, label,
initial, help_text, initial, help_text,
*args, **kwargs) *args, **kwargs)
@ -42,8 +41,7 @@ class LimitedCheckboxField(forms.ModelMultipleChoiceField):
def validate(self, qs): def validate(self, qs):
if qs.count() > self.max_choice: if qs.count() > self.max_choice:
raise forms.ValidationError( raise forms.ValidationError(_("You have selected too much candidates."), code='invalid')
_("You have selected too much candidates."), code='invalid')
# Forms # Forms
@ -66,10 +64,8 @@ class CandidateForm(forms.ModelForm):
can_edit = kwargs.pop('can_edit', False) can_edit = kwargs.pop('can_edit', False)
super(CandidateForm, self).__init__(*args, **kwargs) super(CandidateForm, self).__init__(*args, **kwargs)
if election_id: if election_id:
self.fields['role'].queryset = Role.objects.filter( self.fields['role'].queryset = Role.objects.filter(election__id=election_id).all()
election__id=election_id).all() self.fields['election_list'].queryset = ElectionList.objects.filter(election__id=election_id).all()
self.fields['election_list'].queryset \
= ElectionList.objects.filter(election__id=election_id).all()
if not can_edit: if not can_edit:
self.fields['user'].widget = forms.HiddenInput() self.fields['user'].widget = forms.HiddenInput()
@ -81,13 +77,11 @@ class VoteForm(forms.Form):
for role in election.roles.all(): for role in election.roles.all():
cand = role.candidatures cand = role.candidatures
if role.max_choice > 1: if role.max_choice > 1:
self.fields[role.title] = LimitedCheckboxField( self.fields[role.title] = LimitedCheckboxField(cand, role.max_choice, required=False)
cand, role.max_choice, required=False)
else: else:
self.fields[role.title] \ self.fields[role.title] = forms.ModelChoiceField(cand, required=False,
= forms.ModelChoiceField(cand, required=False, widget=forms.RadioSelect(),
widget=forms.RadioSelect(), empty_label=_("Blank vote"))
empty_label=_("Blank vote"))
class RoleForm(forms.ModelForm): class RoleForm(forms.ModelForm):
@ -109,8 +103,7 @@ class RoleForm(forms.ModelForm):
election = cleaned_data.get('election') election = cleaned_data.get('election')
if Role.objects.filter(title=title, election=election).exists(): if Role.objects.filter(title=title, election=election).exists():
raise forms.ValidationError( raise forms.ValidationError(
_("This role already exists for this election"), _("This role already exists for this election"), code='invalid')
code='invalid')
class ElectionListForm(forms.ModelForm): class ElectionListForm(forms.ModelForm):
@ -122,8 +115,7 @@ class ElectionListForm(forms.ModelForm):
election_id = kwargs.pop('election_id', None) election_id = kwargs.pop('election_id', None)
super(ElectionListForm, self).__init__(*args, **kwargs) super(ElectionListForm, self).__init__(*args, **kwargs)
if election_id: if election_id:
self.fields['election'].queryset = Election.objects.filter( self.fields['election'].queryset = Election.objects.filter(id=election_id).all()
id=election_id).all()
class ElectionForm(forms.ModelForm): class ElectionForm(forms.ModelForm):
@ -142,18 +134,14 @@ class ElectionForm(forms.ModelForm):
'candidature_groups': CheckboxSelectMultiple 'candidature_groups': CheckboxSelectMultiple
} }
start_date = forms.DateTimeField( start_date = forms.DateTimeField(['%Y-%m-%d %H:%M:%S'], label=_("Start date"),
['%Y-%m-%d %H:%M:%S'], label=_("Start date"), widget=SelectDateTime, required=True)
widget=SelectDateTime, required=True) end_date = forms.DateTimeField(['%Y-%m-%d %H:%M:%S'], label=_("End date"),
end_date = forms.DateTimeField( widget=SelectDateTime, required=True)
['%Y-%m-%d %H:%M:%S'], label=_("End date"), start_candidature = forms.DateTimeField(['%Y-%m-%d %H:%M:%S'], label=_("Start candidature"),
widget=SelectDateTime, required=True) widget=SelectDateTime, required=True)
start_candidature = forms.DateTimeField( end_candidature = forms.DateTimeField(['%Y-%m-%d %H:%M:%S'], label=_("End candidature"),
['%Y-%m-%d %H:%M:%S'], label=_("Start candidature"), widget=SelectDateTime, required=True)
widget=SelectDateTime, required=True)
end_candidature = forms.DateTimeField(
['%Y-%m-%d %H:%M:%S'], label=_("End candidature"),
widget=SelectDateTime, required=True)
# Display elections # Display elections
@ -169,8 +157,7 @@ class ElectionsListView(CanViewMixin, ListView):
template_name = 'election/election_list.jinja' template_name = 'election/election_list.jinja'
def get_queryset(self): def get_queryset(self):
return super(ElectionsListView, return super(ElectionsListView, self).get_queryset().filter(archived=False).all()
self).get_queryset().filter(archived=False).all()
class ElectionListArchivedView(CanViewMixin, ListView): class ElectionListArchivedView(CanViewMixin, ListView):
@ -183,8 +170,7 @@ class ElectionListArchivedView(CanViewMixin, ListView):
template_name = 'election/election_list.jinja' template_name = 'election/election_list.jinja'
def get_queryset(self): def get_queryset(self):
return super(ElectionListArchivedView, return super(ElectionListArchivedView, self).get_queryset().filter(archived=True).all()
self).get_queryset().filter(archived=True).all()
class ElectionDetailView(CanViewMixin, DetailView): class ElectionDetailView(CanViewMixin, DetailView):
@ -222,8 +208,7 @@ class VoteFormView(CanCreateMixin, FormView):
# If we have a multiple choice field # If we have a multiple choice field
if isinstance(election_data[role_title], QuerySet): if isinstance(election_data[role_title], QuerySet):
if election_data[role_title].count() > 0: if election_data[role_title].count() > 0:
vote = Vote(role=election_data[ vote = Vote(role=election_data[role_title].first().role)
role_title].first().role)
vote.save() vote.save()
for el in election_data[role_title]: for el in election_data[role_title]:
vote.candidature.add(el) vote.candidature.add(el)
@ -277,8 +262,7 @@ class CandidatureCreateView(CanCreateMixin, CreateView):
def dispatch(self, request, *arg, **kwargs): def dispatch(self, request, *arg, **kwargs):
self.election = get_object_or_404(Election, pk=kwargs['election_id']) self.election = get_object_or_404(Election, pk=kwargs['election_id'])
return super(CandidatureCreateView, return super(CandidatureCreateView, self).dispatch(request, *arg, **kwargs)
self).dispatch(request, *arg, **kwargs)
def get_initial(self): def get_initial(self):
init = {} init = {}
@ -298,8 +282,7 @@ class CandidatureCreateView(CanCreateMixin, CreateView):
""" """
obj = form.instance obj = form.instance
obj.election = Election.objects.get(id=self.election.id) obj.election = Election.objects.get(id=self.election.id)
if(obj.election.can_candidate(obj.user)) and \ if(obj.election.can_candidate(obj.user)) and (obj.user == self.request.user or self.can_edit):
(obj.user == self.request.user or self.can_edit):
return super(CreateView, self).form_valid(form) return super(CreateView, self).form_valid(form)
raise PermissionDenied raise PermissionDenied
@ -309,8 +292,7 @@ class CandidatureCreateView(CanCreateMixin, CreateView):
return kwargs return kwargs
def get_success_url(self, **kwargs): def get_success_url(self, **kwargs):
return reverse_lazy('election:detail', return reverse_lazy('election:detail', kwargs={'election_id': self.election.id})
kwargs={'election_id': self.election.id})
class ElectionCreateView(CanCreateMixin, CreateView): class ElectionCreateView(CanCreateMixin, CreateView):
@ -321,8 +303,7 @@ class ElectionCreateView(CanCreateMixin, CreateView):
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
if not request.user.is_subscribed: if not request.user.is_subscribed:
raise PermissionDenied raise PermissionDenied
return super(ElectionCreateView, return super(ElectionCreateView, self).dispatch(request, *args, **kwargs)
self).dispatch(request, *args, **kwargs)
def form_valid(self, form): def form_valid(self, form):
""" """
@ -332,8 +313,7 @@ class ElectionCreateView(CanCreateMixin, CreateView):
return super(CreateView, self).form_valid(form) return super(CreateView, self).form_valid(form)
def get_success_url(self, **kwargs): def get_success_url(self, **kwargs):
return reverse_lazy('election:detail', return reverse_lazy('election:detail', kwargs={'election_id': self.object.id})
kwargs={'election_id': self.object.id})
class RoleCreateView(CanCreateMixin, CreateView): class RoleCreateView(CanCreateMixin, CreateView):
@ -369,8 +349,7 @@ class RoleCreateView(CanCreateMixin, CreateView):
return kwargs return kwargs
def get_success_url(self, **kwargs): def get_success_url(self, **kwargs):
return reverse_lazy('election:detail', return reverse_lazy('election:detail', kwargs={'election_id': self.object.election.id})
kwargs={'election_id': self.object.election.id})
class ElectionListCreateView(CanCreateMixin, CreateView): class ElectionListCreateView(CanCreateMixin, CreateView):
@ -382,8 +361,7 @@ class ElectionListCreateView(CanCreateMixin, CreateView):
self.election = get_object_or_404(Election, pk=kwargs['election_id']) self.election = get_object_or_404(Election, pk=kwargs['election_id'])
if not self.election.is_vote_editable: if not self.election.is_vote_editable:
raise PermissionDenied raise PermissionDenied
return super(ElectionListCreateView, return super(ElectionListCreateView, self).dispatch(request, *arg, **kwargs)
self).dispatch(request, *arg, **kwargs)
def get_initial(self): def get_initial(self):
init = {} init = {}
@ -410,8 +388,7 @@ class ElectionListCreateView(CanCreateMixin, CreateView):
raise PermissionDenied raise PermissionDenied
def get_success_url(self, **kwargs): def get_success_url(self, **kwargs):
return reverse_lazy('election:detail', return reverse_lazy('election:detail', kwargs={'election_id': self.object.election.id})
kwargs={'election_id': self.object.election.id})
# Update view # Update view
@ -425,30 +402,25 @@ class ElectionUpdateView(CanEditMixin, UpdateView):
def get_initial(self): def get_initial(self):
init = {} init = {}
try: try:
init['start_date'] = self.object.start_date.strftime( init['start_date'] = self.object.start_date.strftime('%Y-%m-%d %H:%M:%S')
'%Y-%m-%d %H:%M:%S')
except Exception: except Exception:
pass pass
try: try:
init['end_date'] = self.object.end_date.strftime( init['end_date'] = self.object.end_date.strftime('%Y-%m-%d %H:%M:%S')
'%Y-%m-%d %H:%M:%S')
except Exception: except Exception:
pass pass
try: try:
init['start_candidature'] = self.object.start_candidature.strftime( init['start_candidature'] = self.object.start_candidature.strftime('%Y-%m-%d %H:%M:%S')
'%Y-%m-%d %H:%M:%S')
except Exception: except Exception:
pass pass
try: try:
init['end_candidature'] = self.object.end_candidature.strftime( init['end_candidature'] = self.object.end_candidature.strftime('%Y-%m-%d %H:%M:%S')
'%Y-%m-%d %H:%M:%S')
except Exception: except Exception:
pass pass
return init return init
def get_success_url(self, **kwargs): def get_success_url(self, **kwargs):
return reverse_lazy('election:detail', return reverse_lazy('election:detail', kwargs={'election_id': self.object.id})
kwargs={'election_id': self.object.id})
class CandidatureUpdateView(CanEditMixin, UpdateView): class CandidatureUpdateView(CanEditMixin, UpdateView):
@ -475,8 +447,7 @@ class CandidatureUpdateView(CanEditMixin, UpdateView):
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
self.form = self.get_form() self.form = self.get_form()
self.remove_fields() self.remove_fields()
if request.user.is_authenticated() and \ if request.user.is_authenticated() and request.user.can_edit(self.object) and self.form.is_valid():
request.user.can_edit(self.object) and self.form.is_valid():
return super(CandidatureUpdateView, self).form_valid(self.form) return super(CandidatureUpdateView, self).form_valid(self.form)
return self.form_invalid(self.form) return self.form_invalid(self.form)
@ -486,9 +457,7 @@ class CandidatureUpdateView(CanEditMixin, UpdateView):
return kwargs return kwargs
def get_success_url(self, **kwargs): def get_success_url(self, **kwargs):
return reverse_lazy('election:detail', return reverse_lazy('election:detail', kwargs={'election_id': self.object.role.election.id})
kwargs={'election_id':
self.object.role.election.id})
class RoleUpdateView(CanEditMixin, UpdateView): class RoleUpdateView(CanEditMixin, UpdateView):
@ -516,8 +485,7 @@ class RoleUpdateView(CanEditMixin, UpdateView):
self.object = self.get_object() self.object = self.get_object()
self.form = self.get_form() self.form = self.get_form()
self.remove_fields() self.remove_fields()
if request.user.is_authenticated() and \ if request.user.is_authenticated() and request.user.can_edit(self.object) and self.form.is_valid():
request.user.can_edit(self.object) and self.form.is_valid():
return super(RoleUpdateView, self).form_valid(self.form) return super(RoleUpdateView, self).form_valid(self.form)
return self.form_invalid(self.form) return self.form_invalid(self.form)
@ -527,8 +495,7 @@ class RoleUpdateView(CanEditMixin, UpdateView):
return kwargs return kwargs
def get_success_url(self, **kwargs): def get_success_url(self, **kwargs):
return reverse_lazy('election:detail', return reverse_lazy('election:detail', kwargs={'election_id': self.object.election.id})
kwargs={'election_id': self.object.election.id})
# Delete Views # Delete Views
@ -540,8 +507,7 @@ class ElectionDeleteView(DeleteView):
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
if request.user.is_root: if request.user.is_root:
return super(ElectionDeleteView, return super(ElectionDeleteView, self).dispatch(request, *args, **kwargs)
self).dispatch(request, *args, **kwargs)
raise PermissionDenied raise PermissionDenied
def get_success_url(self, **kwargs): def get_success_url(self, **kwargs):
@ -556,15 +522,12 @@ class CandidatureDeleteView(CanEditMixin, DeleteView):
def dispatch(self, request, *arg, **kwargs): def dispatch(self, request, *arg, **kwargs):
self.object = self.get_object() self.object = self.get_object()
self.election = self.object.role.election self.election = self.object.role.election
if not self.election.can_candidate \ if not self.election.can_candidate or not self.election.is_vote_editable:
or not self.election.is_vote_editable:
raise PermissionDenied raise PermissionDenied
return super(CandidatureDeleteView, return super(CandidatureDeleteView, self).dispatch(request, *arg, **kwargs)
self).dispatch(request, *arg, **kwargs)
def get_success_url(self, **kwargs): def get_success_url(self, **kwargs):
return reverse_lazy('election:detail', return reverse_lazy('election:detail', kwargs={'election_id': self.election.id})
kwargs={'election_id': self.election.id})
class RoleDeleteView(CanEditMixin, DeleteView): class RoleDeleteView(CanEditMixin, DeleteView):
@ -580,5 +543,4 @@ class RoleDeleteView(CanEditMixin, DeleteView):
return super(RoleDeleteView, self).dispatch(request, *arg, **kwargs) return super(RoleDeleteView, self).dispatch(request, *arg, **kwargs)
def get_success_url(self, **kwargs): def get_success_url(self, **kwargs):
return reverse_lazy('election:detail', return reverse_lazy('election:detail', kwargs={'election_id': self.election.id})
kwargs={'election_id': self.election.id})