from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, Http404
from .models import Article, Comment
from django.urls import reverse

def index(request):
	latest_articles_list = Article.objects.order_by('-pub_date')[:5]
	return render(request, 'firstApp/list.html', {'latest_articles_list': latest_articles_list})
	#return HttpResponse('Hello World!')

def detail(request, article_id):
	try:
		a = Article.objects.get(id = article_id)
	except:
		raise Http404('Статья не найдена')

	latest_comments_list = a.comment_set.all()[:15]

	return render(request, 'firstApp/detail.html', {'article': a, 'l_c_l': latest_comments_list})

def leave_comment(request, article_id):
	try:
		a = Article.objects.get(id = article_id)
	except:
		raise Http404('Статья не найдена')

	a.comment_set.create(text = request.POST['text'], author_name = request.POST['name'])

	return HttpResponseRedirect(reverse('firstApp:detail', args = (a.id,)))