2018-05-21 23:12:35 +02:00
|
|
|
from django.contrib import messages
|
2018-05-21 22:04:29 +02:00
|
|
|
from django.shortcuts import get_object_or_404
|
2018-05-21 23:12:35 +02:00
|
|
|
from django.urls import reverse
|
|
|
|
from django.views.generic import CreateView, ListView
|
2018-05-21 19:28:36 +02:00
|
|
|
|
2018-05-21 22:23:53 +02:00
|
|
|
from manuels.forms import AddBookForm
|
|
|
|
from manuels.models import Teacher, Book
|
2018-05-21 21:03:08 +02:00
|
|
|
|
|
|
|
|
|
|
|
class HomePageView(CreateView):
|
|
|
|
model = Teacher
|
2018-05-21 22:04:29 +02:00
|
|
|
fields = ['first_name', 'last_name', 'phone_number']
|
2018-05-21 21:03:08 +02:00
|
|
|
template_name = 'manuels/home_page.html'
|
2018-05-21 22:04:29 +02:00
|
|
|
|
|
|
|
|
2018-05-21 23:12:35 +02:00
|
|
|
class BaseTeacherView:
|
2018-05-21 22:23:53 +02:00
|
|
|
teacher = None
|
|
|
|
|
|
|
|
def dispatch(self, request, *args, **kwargs):
|
2018-05-21 23:23:43 +02:00
|
|
|
self.teacher = get_object_or_404(Teacher, pk=self.kwargs['pk'])
|
2018-05-21 22:23:53 +02:00
|
|
|
return super().dispatch(request, *args, **kwargs)
|
2018-05-21 22:04:29 +02:00
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
context = super().get_context_data()
|
2018-05-21 22:23:53 +02:00
|
|
|
context['teacher'] = self.teacher
|
2018-05-21 22:04:29 +02:00
|
|
|
|
|
|
|
return context
|
2018-05-21 22:23:53 +02:00
|
|
|
|
2018-05-21 23:12:35 +02:00
|
|
|
|
|
|
|
class ListBooksView(BaseTeacherView, ListView):
|
|
|
|
model = Book
|
|
|
|
template_name = 'manuels/list_books.html'
|
|
|
|
context_object_name = 'books'
|
|
|
|
|
|
|
|
def get_queryset(self):
|
|
|
|
return Book.objects.filter(teacher=self.teacher)
|
|
|
|
|
|
|
|
|
|
|
|
class AddBookView(BaseTeacherView, CreateView):
|
|
|
|
model = Book
|
|
|
|
template_name = 'manuels/add_book.html'
|
|
|
|
form_class = AddBookForm
|
|
|
|
add_another = False
|
|
|
|
|
2018-05-21 22:23:53 +02:00
|
|
|
def get_initial(self):
|
|
|
|
return {
|
|
|
|
'teacher': self.teacher
|
|
|
|
}
|
|
|
|
|
|
|
|
def get_form(self, form_class=None):
|
|
|
|
form = super().get_form(form_class)
|
|
|
|
form.fields['teacher'].queryset = Teacher.objects.filter(pk=self.teacher.pk)
|
|
|
|
return form
|
2018-05-21 23:12:35 +02:00
|
|
|
|
|
|
|
def form_valid(self, form):
|
|
|
|
self.add_another = form.cleaned_data['add_another']
|
|
|
|
return super().form_valid(form)
|
|
|
|
|
|
|
|
def get_success_url(self):
|
|
|
|
messages.success(self.request, f'"{self.object}" a été ajouté.')
|
|
|
|
if self.add_another:
|
2018-05-21 23:23:43 +02:00
|
|
|
return reverse('add_book', args=[str(self.teacher.pk)])
|
2018-05-21 23:12:35 +02:00
|
|
|
else:
|
2018-05-21 23:23:43 +02:00
|
|
|
return reverse('list_books', args=[str(self.teacher.pk)])
|