Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django form - pass request.user into widget render function

How would I pass the request.user object into the render function of a custom widget I have created, or what is the best way to access the current user from within the render function

like image 708
John Avatar asked Dec 13 '22 15:12

John


1 Answers

Solution I believe is not yet a hack (but close to) and is not that big hassle.

  1. Override init on your forms:

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super(SomeForm, self).__init__(*args, **kwargs)
        self.fields['your_field'].widget.user = user
    
  2. Override your widget:

    def __init__(self, *args, **kwargs):
        self.user = None
        super(YourWidget, self).__init__(*args, **kwargs)
    
  3. Make profit with your user on a widget.

Obviously you need provide user to a form, and this on some edge cases might be a problem, for example you are using django dynamic views and you hate to change them to somewhat more static approach.

like image 136
Drachenfels Avatar answered Jan 29 '23 06:01

Drachenfels