--- /dev/null
+from django import forms
+from .models import Post
+
+class PostForm(forms.ModelForm):
+
+ class Meta:
+ model = Post
+ fields = ('title', 'text')
+
\ No newline at end of file
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
+ url(r'^post/new/$', views.post_new, name='post_new'),
+ url(r'^post/(?P<pk>\d+)/edit/$', views.post_edit, name='post_edit'),
]
\ No newline at end of file
-from django.shortcuts import render, get_object_or_404
+from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import Post
+from .forms import PostForm
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
+
+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()
+ return redirect('post_detail', pk=post.pk)
+ else:
+ form = PostForm()
+ return render(request, 'blog/post_edit.html', {'form': form})
+
+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()
+ return redirect('post_detail', pk=post.pk)
+ else:
+ form = PostForm(instance=post)
+ return render(request, 'blog/post_edit.html', {'form': form})