depot/web/quotes/quotedb/views.py

62 lines
1.7 KiB
Python
Raw Permalink Normal View History

2021-01-20 23:14:58 +00:00
from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404, render, redirect
from django.forms import ModelForm
2021-01-19 03:51:22 +00:00
2021-01-20 22:20:07 +00:00
from . import models
2021-01-19 03:51:22 +00:00
def home(request):
2021-01-20 22:20:07 +00:00
random_quote = models.Quote.objects.all().order_by("?").first()
return render(
request,
"quotedb/home.html",
{
"quote": random_quote,
},
)
2021-01-20 23:14:58 +00:00
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
2021-01-20 22:48:41 +00:00
fields = ["quote"]
def add_quote(request):
2021-01-20 22:48:41 +00:00
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})
2021-01-20 23:14:58 +00:00
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})