
You’ve secured your views. Now you have a new problem. When a user creates a new post, how do you save who that user was? You can’t add author to the fields listโthat would create a dropdown menu of all users!
The solution is to tell the view: “When you save the form, automatically set the author to the user who sent the request.”
We do this by overriding the form_valid method in our CreateView.
The Setup
- Your
Postmodel has anauthorfield (a ForeignKey to the User model). - Your
CreateViewis protected byLoginRequiredMixin.
The form_valid Method
This method is called after Django checks that the form is valid, but before it saves. It’s the perfect place to inject our data.
pages/views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic
from .models import Post
class PostCreateView(LoginRequiredMixin, generic.CreateView):
model = Post
fields = ['title', 'text'] # Note: 'author' is NOT in the form
template_name = 'pages/post_new.html'
# This is the new method you add:
def form_valid(self, form):
# 1. Set the author of the new post to the current user
form.instance.author = self.request.user
# 2. Let the parent class (CreateView) do the rest
return super().form_valid(form)How It Works
- The user (who is logged in, thanks to
LoginRequiredMixin) submits the form with atitleandtext. form_validis called.- We access the new post object before it’s saved using
form.instance. - We set
form.instance.authortoself.request.user(which Django provides automatically). super().form_valid(form)is called, which saves the now-complete object to the database.
This is the secure, standard way to handle user-generated content.
Key Takeaways
- To save the post author when a user creates a new post in Django, override the form_valid method in CreateView.
- Ensure your Post model includes an author field linked to the User model using ForeignKey.
- Use LoginRequiredMixin to restrict access to the CreateView for logged-in users.
- In the form_valid method, set form.instance.author to self.request.user before calling super().form_valid(form) to save the post.
- This approach securely associates a post with the user who created it.





