Write Views
There is a file named views.py in our app directory (blog).
Let's Create view functions named signUp, signIn, createPost, getAllPosts, getPostById and Comments
Add following code in your blog/views.py.
blog/views.py
def signup(request):
if request.method == 'GET':
signupForm = UserForm()
return render(request, 'signup.html', {'signupForm': signupForm})
if request.method == 'POST':
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
user = User.objects.create(username=username, email=email, password=password)
if user is not None:
return HttpResponse("user created successfully.")
return HttpResponse("Sorry user not created.")
def signin(request):
if request.method == 'GET':
loginForm = LoginForm()
return render(request, 'signin.html', {'loginForm': loginForm})
if request.method =='POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate( username=username, password=password)
if user is not None:
login(request, user)
return HttpResponse("user logged in successfully.")
return HttpResponse("user not found.")
def create_post(request):
if request.method == 'GET':
blogForm = BlogForm()
return render(request, 'create_post.html', {'postForm': blogForm})
if request.method == 'POST':
title = request.POST['title']
content = request.POST['content']
image = request.POST['image']
author= request.user
blog = Blog.objects.create(title=title, content=content, image=image, author=author)
return HttpResponse("Hello, World. You're at the blog's createPost Page.")
def get_all_posts(request):
posts = Blog.objects.all()
return HttpResponse("Hello, World. You're at the blog's getAllPosts Page.")
def get_post_by_id(request,id):
commentForm = CommentForm()
post = Blog.objects.get(id=id)
comments = Comment.objects.filter(blog=post)
return render(request, 'post_detail.html', {'post': post, 'comments': comments, 'commentForm': commentForm})
def comment(request, id):
if request.method == 'POST':
comment = request.POST['comment']
author= request.user
blog = Blog.objects.get(id=id)
comment = Comment.objects.create(comment=comment, blog=blog, author=author)
return HttpResponse("Hello, World. You're at the blog's comment Page.")
tip
Add an import for models using following line of code.
from . models import *