from django.core.paginator import Paginator from django.shortcuts import get_object_or_404, render, redirect from django.forms import ModelForm from . import models def home(request): random_quote = models.Quote.objects.all().order_by("?").first() return render( request, "quotedb/home.html", { "quote": random_quote, }, ) def list_quotes(request): quotes = models.Quote.objects.all().order_by("-pk") items_per_page = 10 p = Paginator(quotes, items_per_page) try: page_num = int(request.GET.get("page", "1"), 10) except: page_num = 1 page = p.page(page_num) return render(request, "quotedb/list.html", {"paginator": p, "page": page}) def show_quote(request, quote_id): quote = get_object_or_404(models.Quote, id=int(quote_id)) return render(request, "quotedb/show_quote.html", {"quote": quote}) class AddQuoteForm(ModelForm): class Meta: model = models.Quote fields = ["quote"] def add_quote(request): if request.method == "POST": form = AddQuoteForm(request.POST) if form.is_valid(): new_quote = form.save(commit=False) new_quote.added_by = request.user new_quote.save() return redirect(new_quote) else: form = AddQuoteForm() return render(request, "quotedb/new.html", {"form": form}) def delete_quote(request, quote_id): quote = get_object_or_404(models.Quote, id=int(quote_id), added_by=request.user) if request.method == "POST": quote.delete() return render(request, "quotedb/deleted_quote.html", {"quote_id": quote_id}) return render(request, "quotedb/delete_quote.html", {"quote": quote})