V
V
Viktor Yurchenko2018-02-01 01:48:39
Django
Viktor Yurchenko, 2018-02-01 01:48:39

How to get current user data in form?

When I create an article, I get a list of all blogs. And you need to get only a list of blogs created by the user. I am creating a form based on a model. I use this function when limiting the sample. Everything works, only the problem is how to get data about the user who is currently authorized.

def __init__(self, *args, **kwargs):
        super(BlogPostNewForms, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['blog'].queryset = MyBlog.objects.filter(author=MyProfile.objects.get(user=ИМЯ_ТЕКУЩЕГО_ПОЛЬЗОВАТЕЛЯ))

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2018-02-01
@sim3x

self.request.user
self.user

D
Dmitry Matveev, 2018-02-01
@Shlem

In the init form, before *args, add one more argument user_id=None
In the view, when initializing the form, pass request.user.id there
In the init, check - if there is a user_id, then filter the queryset

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question