Write Views
There is a file named views.py in our app directory (blog).
Let's Create view functions named signup, signin, create_post, get_all_posts, get_post_by_id and comment. Together with the home view from the Getting Started topic, these cover every URL we wired up in the previous topic.
Add following code in your blog/views.py.
blog/views.py
from django.contrib.auth import authenticate, login
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from .forms import BlogForm, CommentForm, LoginForm, SignUpForm
from .models import Blog, Comment
def home(request):
return HttpResponse("Hello, World. You're at the blog's home Page.")
def signup(request):
if request.method == 'POST':
signupForm = SignUpForm(request.POST)
if signupForm.is_valid():
signupForm.save()
return redirect('signin')
return render(request, 'signup.html', {'signupForm': signupForm})
signupForm = SignUpForm()
return render(request, 'signup.html', {'signupForm': signupForm})
def signin(request):
if request.method == 'POST':
loginForm = LoginForm(request.POST)
if loginForm.is_valid():
user = authenticate(
request,
username=loginForm.cleaned_data['username'],
password=loginForm.cleaned_data['password'],
)
if user is not None:
login(request, user)
return redirect('posts')
return HttpResponse("Invalid username or password.")
loginForm = LoginForm()
return render(request, 'signin.html', {'loginForm': loginForm})
def create_post(request):
if request.method == 'POST':
blogForm = BlogForm(request.POST, request.FILES)
if blogForm.is_valid():
blog = blogForm.save(commit=False)
blog.author = request.user
blog.save()
return redirect('post', id=blog.id)
return render(request, 'create_post.html', {'postForm': blogForm})
blogForm = BlogForm()
return render(request, 'create_post.html', {'postForm': blogForm})
def get_all_posts(request):
posts = Blog.objects.all()
return render(request, 'posts.html', {'posts': posts})
def get_post_by_id(request, id):
post = get_object_or_404(Blog, id=id)
comments = Comment.objects.filter(blog=post)
commentForm = CommentForm()
return render(
request,
'post_detail.html',
{'post': post, 'comments': comments, 'commentForm': commentForm},
)
def comment(request, id):
blog = get_object_or_404(Blog, id=id)
if request.method == 'POST':
commentForm = CommentForm(request.POST)
if commentForm.is_valid():
new_comment = commentForm.save(commit=False)
new_comment.blog = blog
new_comment.author = request.user
new_comment.save()
return redirect('post', id=blog.id)
A few things worth noticing:
signupsaves the user throughSignUpForm(built on Django'sUserCreationForm), so the password is validated and stored as a secure hash — never in plain text.signinusesauthenticate()andlogin()fromdjango.contrib.auth.authenticate()checks the submitted password against the stored hash and returns the user (orNone), andlogin()attaches that user to the session.create_postandcommentsetauthor = request.user, so you must be signed in before calling them — sign up and sign in first when you test the app.get_object_or_404returns the object or raises a proper 404 page instead of an unhandledDoesNotExisterror.commentkeeps theidparameter thatpost/<int:id>/comments/passes to it, then redirects back to the post detail page.
note
The forms (SignUpForm, LoginForm, BlogForm, CommentForm) are written in the next topic, and the templates (signup.html, posts.html, ...) in the last one. Write them before starting the server, otherwise the imports and render() calls will fail.