[Django]-How to pass logged user's id to CreateView

6👍

You can patch the object in the form_valid method:

from django.contrib.auth.mixins import LoginRequiredMixin

class PostCreate(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['headline', 'quote']
    success_url = '/index'
    template_name = 'base_homepage.html'
    
    def get_context_data(self, **kwargs):
        kwargs['latest_posts_list'] = Post.objects.order_by('-id')
        return super(PostCreate, self).get_context_data(**kwargs)

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

Note: You can limit views to a class-based view to authenticated users with the
LoginRequiredMixin mixin [Django-doc].


Note: The documentation advises to
use the AUTH_USER_MODEL setting [Django-doc] over
get_user_model() [Django-doc].
This is safer, since if the authentication app is not yet loaded, the settings
can still specify the name of the model. Therefore it is better to write:

from django.conf import settings

class Post(models.Model):
    # …
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )

Leave a comment