Lesson 5: User Registration – Because Only the Worthy Should Comment!
Ah, you’ve made it this far! 🧙♂️ Your blog is now running, posts are going live, and comments are rolling in (hopefully). But wait—should just anyone be allowed to comment? No, no, no! We need some exclusivity. Only the registered, worthy souls should get the power to share their wisdom (or pizza topping opinions 🍕).
In this lesson, we’ll add user registration so that visitors can sign up, log in, and get commenting. And while we’re at it, we’ll make sure only registered users can leave comments. Ready? Let’s do this!
Step 1: Activate the Virtual Environment (Get the Magic Started)
First things first, make sure your virtual environment is activated. This is your safety net to ensure all dependencies are working smoothly.
If you’re not already inside it, run:
source venv/bin/activate
Once you see (venv)
at the start of your terminal prompt, you’re ready to proceed. 🧙♂️
Step 2: Update forms.py
to Remove the author
Field and Add CustomUserCreationForm
Now we’ll update the form to remove the author
field from CommentForm
and define our custom user registration form for user sign-up.
File path: myblog/blog/forms.py
Update your forms.py
to look like this:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from .models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['content'] # Only include the comment content field
class CustomUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
With this setup:
- We’re now only asking for the comment’s content in the form, and the author will be set automatically (no need for the user to type their own name).
- We have a
CustomUserCreationForm
that adds an email field to the registration form.
Step 3: Modify the blog_post_detail
View to Handle the Logged-In User as Author
Since the form no longer asks for the author
, we’ll assign the logged-in user as the comment’s author in the view.
File path: myblog/blog/views.py
Here’s how to update the blog_post_detail
view:
from django.shortcuts import render, get_object_or_404, redirect
from .models import BlogPost, Comment
from .forms import CommentForm
def blog_post_detail(request, pk):
post = get_object_or_404(BlogPost, pk=pk)
comments = post.comments.all()
if request.method == 'POST':
if request.user.is_authenticated:
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.blog_post = post
comment.author = request.user.username # Automatically assign the logged-in user as the author
comment.save()
return redirect('blog_post_detail', pk=post.pk)
else:
return redirect('login') # Redirect to login if the user is not authenticated
else:
form = CommentForm()
return render(request, 'blog_post_detail.html', {'post': post, 'comments': comments, 'form': form})
Step 4: Create the register
View to Handle User Sign-Up
Let’s create the registration view, which will use our CustomUserCreationForm
. After registering, the user will be automatically logged in and redirected to the blog index page.
File path: myblog/blog/views.py
Add this code to create the registration view:
from django.contrib.auth import login
def register(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user) # Automatically log them in after registering
return redirect('blog_index')
else:
form = CustomUserCreationForm()
return render(request, 'registration/register.html', {'form': form})
Step 5: Create the Registration Template
We need to create a simple template for the registration page so users can input their username, email, and password.
File path:
myblog/
blog/
templates/
registration/
register.html
Here’s the content for register.html
:
{% extends "base.html" %}
{% block title %}Register{% endblock %}
{% block content %}
<h2>Create an Account</h2>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign Up</button>
</form>
{% endblock %}
Step 6: Update urls.py
to Include Registration and Blog Routes
Next, we’ll add the route to our registration page in urls.py
.
File path: myblog/blog/urls.py
In urls.py
, add the following routes:
from . import views
urlpatterns = [
path('', views.blog_index, name='blog_index'),
path('post/<int:pk>/', views.blog_post_detail, name='blog_post_detail'),
path('register/', views.register, name='register'), # Registration page
]
Now the registration page is accessible at /register/
.
Step 7: Update the Comment Form in blog_post_detail.html
Let’s make sure that only logged-in users can comment, and non-logged-in users are redirected to log in or register.
File path:
myblog/
blog/
templates/
blog_post_detail.html
Update the comment section in blog_post_detail.html
:
<h3>Comments</h3>
<ul>
{% for comment in comments %}
<li><strong>{{ comment.author }}</strong>: {{ comment.content }}</li>
{% empty %}
<li>No comments yet. Be the first to share your thoughts!</li>
{% endfor %}
</ul>
{% if user.is_authenticated %}
<h3>Leave a Comment</h3>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% else %}
<p><a href="{% url 'login' %}">Login</a> or <a href="{% url 'register' %}">register</a> to leave a comment!</p>
{% endif %}
This ensures that only logged-in users can leave comments.
Step 8: Test the Registration and Comment Process
Once all the changes are made, start your server and test the registration and comment features by running:
python3 manage.py runserver
Visit http://127.0.0.1:8000/register/ to sign up, and then try commenting on a blog post as a logged-in user.
Step 9: Deactivate the Virtual Environment (Don’t Forget)
When you’re done testing, don’t forget to deactivate your virtual environment:
deactivate
That’s it for today’s lesson! 🧙♂️
Conclusion of Lesson 5
Boom! 🎉 You’ve successfully integrated user registration and made sure only logged-in users can leave comments. No more anonymous trolls sneaking into your blog’s comment section! You’ve also cleaned up the CommentForm
and ensured the CustomUserCreationForm
is handling registration like a charm.
Next up, we’ll dive into user profiles—because every user deserves a bit of personality on your blog. Until then, enjoy watching your registered user base grow! 🎩✨
See also
- Lesson 6: User Profiles – Because Everyone Deserves a Little Spotlight
- Lesson 4: User Authentication – Because Not Everyone Should Have Access to Your Blog's Inner Sanctum
- Lesson 3: Forms – The Art of Asking Nicely for User Input (Without Scaring Them Away)
- Lesson 2: The Model-View-Template (MVT) Pattern – Like MVC, But With More Magic and Less Headaches
- Django: The Web Framework That'll Make You Feel Like a Code Wizard (Without the Spellbook)