Django Forms: How to Automatically Set the Author on Save

3D visualization of a robotic hand automatically stamping the 'Author' field on a form before it is saved, representing Django form automation.

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 Post model has an author field (a ForeignKey to the User model).
  • Your CreateView is protected by LoginRequiredMixin.

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

  1. The user (who is logged in, thanks to LoginRequiredMixin) submits the form with a title and text.
  2. form_valid is called.
  3. We access the new post object before it’s saved using form.instance.
  4. We set form.instance.author to self.request.user (which Django provides automatically).
  5. 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.

Similar Posts

Leave a Reply