geschichten/stories/writingtogether/views.py

83 lines
2.6 KiB
Python
Raw Normal View History

2021-03-31 01:15:49 +02:00
from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
2021-03-30 21:25:52 +02:00
# Create your views here.
from django.urls import reverse_lazy, reverse
2021-03-31 01:15:49 +02:00
from django.views import generic
from django.views.generic import CreateView, UpdateView, RedirectView
2021-03-31 01:15:49 +02:00
from writingtogether.models import Story, StoryPart, StoryRound, Participant
class IndexView(generic.ListView):
template_name = 'writingtogether/index.html'
2021-04-19 00:19:32 +02:00
context_object_name = 'open_story_round_list'
2021-03-31 01:15:49 +02:00
def get_queryset(self):
2021-04-19 00:19:32 +02:00
# TODO: show open & finished rounds
2021-03-31 01:15:49 +02:00
return StoryRound.objects.order_by('-created')[:5]
class DetailView(generic.DetailView):
model = StoryRound
template_name = 'writingtogether/detail.html'
class StoryRoundCreate(CreateView):
model = StoryRound
fields = ['name', 'participants', 'number_of_rounds']
success_url = reverse_lazy('writing:index')
2021-03-31 01:15:49 +02:00
def form_valid(self, form):
self.object = form.save()
sorted_participants = sorted(form.cleaned_data['participants'])
number_of_participants = len(sorted_participants)
2021-03-31 01:15:49 +02:00
for user in sorted_participants:
story = Story.objects.create(
2021-03-31 01:15:49 +02:00
part_of_round=self.object,
started_by=user
2021-03-31 01:15:49 +02:00
)
previous_part=None
for i in range(form.cleaned_data['number_of_rounds']):
current_part = StoryPart.objects.create(
user=sorted_participants[i % number_of_participants],
previous_part=previous_part,
part_of=story
)
previous_part = current_part
2021-03-31 01:15:49 +02:00
class StoryUpdate(UpdateView):
model = Story
fields = ['name']
class StoryPartUpdate(UpdateView):
2021-03-31 01:15:49 +02:00
model = StoryPart
fields = ['text']
template_name = 'writingtogether/story_part.html'
2021-03-31 01:15:49 +02:00
#def form_valid(self, form):
# form.instance.created_by = self.request.user
# form.instance.previous_part_id = self.kwargs['previous']
# form.instance.part_of_id = self.kwargs['story_pk']
# return super().form_valid(form)
class RedirectToNextOpenPart(RedirectView):
permanent = False
query_string = True
pattern_name = 'writing:update_story_part'
def get_redirect_url(self, *args, **kwargs):
story_round = get_object_or_404(StoryRound, pk=kwargs['story_round_pk'])
story_part = story_round.get_next_story_part(user=self.request.user)
kwargs['story_pk'] = story_part.part_of.pk
kwargs['story_part_pk'] = story_part.pk
return super().get_redirect_url(*args, **kwargs)