django_blog/blog/views.py.save
2017-12-08 00:56:38 +03:00

72 lines
2.9 KiB
Plaintext

# -*- coding: utf-8 -*-
from django.shortcuts import render
from .models import Post
from django.utils import timezone
from django.shortcuts import render, get_object_or_404, render_to_response
from django.shortcuts import redirect
from .forms import PostForm
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.decorators import login_required
def post_list(request, page='1'):
post_list = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')#[int(page)*5-5:int(page)*5]
paginator = Paginator(post_list, 5)
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger: # If page is not an integer, deliver first page.
posts = paginator.page(1)
except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results.
posts = paginator.page(paginator.num_pages)
return render_to_response('blog/post_list.html', {'posts': posts})
def search_by_tag(request, tag):
tagged_posts = Post.objects.filter(tags__name=tag).order_by('-published_date')
return render(request, 'blog/tag_listing.html', {'tagged_posts': tagged_posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
tags = post.tags.names()
if request.POST.get('action') == 'delete':
print request.user.is_authenticated()
post.delete()
return redirect('blog.views.post_list', 1)
return render(request, 'blog/post_detail.html', {'post': post, 'tags': tags})
@login_required(login_url="/admin/login/?next=/blog/")
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
form.save_m2m()
return redirect('blog.views.post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
@login_required(login_url="/admin/login/?next=/blog/")
def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, instance = post)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
#post.published_date = timezone.now()
post.save()
form.save_m2m()
return redirect('blog.views.post_detail', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'blog/post_edit.html', {'form': form})