Volpym
Volpym

Reputation: 161

How to pass logged user's id to CreateView

I can't figure out how to pass current user's name as the post's author automatically.

If add the author fields = ['headline', 'quote', 'author'], the dropdown menu is shown and passed, but I need the logged user's name to be the default.

my view:

class PostCreate(CreateView):
model = Post
user = User
fields = ['headline', 'quote']
success_url = '/index'
template_name = 'base_homepage.html'

@login_required()
def get_context_data(self, **kwargs):
    kwargs['latest_posts_list'] = Post.objects.order_by('-id')
    return super(PostCreate, self).get_context_data(**kwargs)

my model:

class Post(models.Model):
_id = models.ObjectIdField
headline = models.TextField(max_length=255)
quote = models.TextField(max_length=140)

creation_time = models.DateTimeField(editable=False).auto_now_add

author = models.ForeignKey(
    get_user_model(),
    on_delete=models.CASCADE,
)

def __str__(self):
    return self.headline[:25]

Upvotes: 3

Views: 2244

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

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
    )

Upvotes: 6

Related Questions