S
S
Stepan Krapivin2014-01-29 17:06:58
Django
Stepan Krapivin, 2014-01-29 17:06:58

How to determine the current user from the model?

There is a model:

class Post(models.Model):
    title = models.CharField(max_length=127)
    datetime = models.DateTimeField(default=datetime.now())
    author = models.ForeignKey(User)
    content = models.TextField(max_length=4095)

The author field should default to the user creating the entry.
I know what to do through the default parameter, but how to determine the current user ?
PS
Perhaps it would be correct to define the user through the post creation form itself, and not from the model?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sardar, 2014-01-29
@xevin

No, default is not needed there. Most likely your User is from django.contrib.auth.models.User. And this means that you have AuthenticationMiddleware. And this means that you have a user request.user, try to print it from your view. So you can post.author = request.user
Your form most likely does not include a user field, which means you need to save it as post = form.save(commit=False) so that the form writes the data to the post, but does not try to save it. Then you assign the user.
In general, it would be worthwhile to completely go through the tutorial .

D
dibrovsd, 2014-01-30
@dibrovsd

Why didn't the signals work?
The creation of model instances can be initiated via a signal chain or in some other way, and not only through the admin panel.
And what now, write the same code in the admin panel, all views, and so on.
Inside the signal, the following middleware will help you get the current user without accessing the request object:
djangosnippets.org/snippets/2179
It works and does its job.
PS If you need to describe in more detail, speak.
I did not describe in detail, so as not to be K.O.
But if you can’t figure it out on your own, I’m ready to help.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question