Set the current user in a Django CreateView

Often when creating a model via a form in Django you want to relate that object to the currently logged in user, or the business to which the current user relates to in its turn.

You may set the current user for a new object in the form_valid method of a CreateView. Make sure to require a login, otherwise there is no current user to be set.

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import CreateView

from projects.models import Project

class CredentialsCreateView(LoginRequiredMixin, CreateView):
    model = Project
    fields = ['title']

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

See Also

6 Non-Programming Books for Programmers