How can I get current user in ModelForm init()?

django get current user in form
how to associate model with current user while saving
django modelform request user
get user in form
django get current user in model
django admin get current user
add current user to model django
django form request user

I want to show different contents for each user with different privilege, I'm trying to get current user from init() function in ModelForm class, but failed

the code below is my current init() in ModelForm

def __init__(self, *args, **kwargs):

    self.user = kwargs.pop('user',None)
    super(MyForm, self).__init__(*args, **kwargs)

but self.user only works after the form has been sent, like in is_valid() function or in clean_data() function

I always get "None" value of self.user in init() Should I keep trying to get current user in ModelForm init(), or maybe there is a better way to implement that funtionality?

You need to send this Data from View. For example, in a Generic Class Based Edit View you can use get_form_kwargs():

class YourView(FormView):
   form_class = YourForm

   def get_form_kwargs(self):
    kwargs = super(YourView, self).get_form_kwargs()
    kwargs['user'] = self.request.user
    return kwargs

In other scenario, initiate form with passing known argument user:

def some_view(request):
    form = YourForm(request.POST, user=request.user)

django: how to access current request user in ModelForm?, you need to have a __init__ method in the model form class, and you access the request or other parameters from the arguments of the __init__ method, then you need to call the super constructor to new up the form class. and then you set the queryset of the required field. To add to @EAMann's answer, you need to wrap your wp_get_current_user() call (or any call that tries to access a function defined within pluggable.php) within the 'plugins_loaded' action.

f = MyForm(user=request.user) // where you are calling the form in the view

and the constructor will look like:

class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
         self.user = kwargs.pop('user',None)
         super(MyForm, self).__init__(*args, **kwargs)

get request.user in ModelForm � Issue #23 � asifpy/django , Hi asifpy, Could you please help to advise how can I get request.user in def __init__(self, *args, **kwargs): user = kwargs.pop('user',None) actual_model_name : returns the actual model name (person -> person) User Contributed Notes #User Contributed Notes. The call to wp_get_current_user () returns the WP_User object. You can use it from the plugins_loaded hook on. IMPORTANT NOTE: This is for demonstration purposes ONLY. The correct way to determine whether a user is logged in is to use the function is_user_logged_in ().

Create a new file in your project folder and named

from __future__ import absolute_import, division, print_function

    from threading import local
except ImportError:
    from django.utils._threading_local import local

_thread_locals = local()

def get_current_request():
    """ returns the request object for this thread """
    return getattr(_thread_locals, "request", None)

def get_current_user():
    """ returns the current user, if exist, otherwise returns None """
    request = get_current_request()
    if request:
        return getattr(request, "user", None)

class ThreadLocalMiddleware(object):
    """ Simple middleware that adds the request object in thread local stor    age."""

    def process_request(self, request):
        _thread_locals.request = request

    def process_response(self, request, response):
        if hasattr(_thread_locals, 'request'):
    del _thread_locals.request
        return response

Then, config your setting file:

MIDDLEWARE = [ ... 'YOUR_PROJECT_NAME.middleware.ThreadLocalMiddleware', ]

Use the function get_current_user() anywhere you want to get curent user. Example

from YOUR_PROJECT_NAME.middleware import get_current_user


Class SomeModel(models.Model):

    def some_method(self):
        current_user = get_current_user()

Как я могу получить текущего пользователя в ModelForm init()?, Как я могу получить текущего пользователя в ModelForm init()? def __init__( self, *args, **kwargs): self.user = kwargs.pop('user',None) super(MyForm, self). "request", None) def get_current_user(): """ returns the current user, if exist,� current_user_can (string $capability, mixed $args) Returns whether the current user has the specified capability.

Saving a ModelForm for the current user?, ModelForm): def __init__(user, *args, **kwargs): self.user = user super(SiteForm, self).__init__(*args, **kwargs). class Meta: model = Site However, init still waits for one of the above three conditions to occur. To provide for an instantaneous response, the telinit Q or q command can wake up init to re-examine the /etc/inittab file. If init is not in single user mode and receives a powerfail signal (SIGPWR), it reads the file /etc/powerstatus. It then starts a command based on

django: how to access current request user in ModelForm?, f = MyForm(user=request.user). and the constructor will look like: class MyForm( forms.ModelForm): def __init__(self, *args, **kwargs): self.user� It seems like you have two questions which I understand. The first is , why do you have this traceback. I don't know, if you can reproduce it in the test_project then I could debug it.

Django: Current User Id for ModelForm Admin - django - iOS, Django: Current User Id for ModelForm Admin - django. ModelForm): class Meta(object): model = Foo def __init__(self, *args, **kwargs): super(FooForm, self). Karthik i am trying to run this script in Anynomous Mode where everyone has view access to the script library. But i get "Access Denied: You do not have permission to perform this action or access this reources".

  • You have to pass the user to the form obviously - kwargs.pop('user',None) will not automagically insert user in kwargs if it's not been passed.
  • This is a link only answer. Please take (at least) the parts that are required for a minimal working opy from the link and add it to your answer in case the link might become broken in the future.
  • You should give proper attribution (at least the link to where you got this antipattern recipe from) - but it's really an antipattern, Django has been specifically designed to properly decouple the domain from the request/response cycle so your domain code doesn't NEED a request to work (which is the RightThing(tm) to do).