Coverage for author\views.py: 100%
38 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-06-29 10:02 +0100
« prev ^ index » next coverage.py v7.4.4, created at 2024-06-29 10:02 +0100
1from django.contrib import messages
2from django.shortcuts import render, get_object_or_404, redirect
3from django.views import View
5from author.forms import AuthorForm, AuthorFormInput
6from author.models import Author
7from book.models import Book
10class AuthorList(View):
11 def get(self, request):
12 """
13 Retrieves all books and authors from the database and renders the
14 'authors.html' template.
16 Returns:
17 HttpResponse: The rendered template with the author's data.
18 """
19 books = Book.objects.all()
20 authors = Author.objects.all().order_by('id')
21 for author in authors:
22 author.read = any(book.author == author and book.reader
23 for book in books)
24 return render(request, "author/authors.html", {'authors': authors})
26 def post(self, request, author_id):
27 """
28 Handle HTTP POST request to delete an author.
30 Args:
31 request (HttpRequest): The HTTP request object.
32 author_id (int): The ID of the author to be deleted.
34 Returns:
35 HttpResponseRedirect: A redirect response to the 'authors' page.
37 Raises:
38 Http404: If the author with the specified ID does not exist.
39 """
40 author = get_object_or_404(Author, id=author_id)
41 author.delete()
42 messages.add_message(request, messages.SUCCESS,
43 f'{author.name} was removed')
44 return redirect('authors')
47class AuthorDetail(View):
48 def get(self, request, author_id=-1):
49 """
50 Handles the GET request for the author view.
52 Args:
53 request (HttpRequest): The HTTP request object.
54 author_id (int, optional): The ID of the author. Defaults to -1.
56 Returns:
57 HttpResponse: The HTTP response object.
58 """
59 form_input = AuthorFormInput()
60 if author_id >= 0:
61 name = get_object_or_404(Author, id=author_id).name
62 form_input.fields['name'].initial = name
63 return render(request, "author/author.html", {'form_input': form_input,
64 'author_id': author_id})
66 def post(self, request, author_id=-1):
67 """
68 Handle the HTTP POST request for creating or updating an author.
70 Args:
71 request (HttpRequest): The HTTP request object.
72 author_id (int, optional): The ID of the author to be updated.
73 Defaults to -1.
75 Returns:
76 HttpResponseRedirect: A redirect response to the 'authors' page.
78 """
79 if author_id < 0:
80 author_form = AuthorForm(data=request.POST)
81 action_message = 'added'
82 else:
83 author = get_object_or_404(Author, id=author_id)
84 author_form = AuthorForm(data=request.POST, instance=author)
85 action_message = 'updated'
87 if author_form.is_valid():
88 author = author_form.save(commit=False)
89 author.name = request.POST["name"]
90 author.save()
91 messages.add_message(request, messages.SUCCESS,
92 f'{author.name} was {action_message}')
93 return redirect('authors')