Using request.user in Forms.py

I dont know how to make this possible
Any advice on how to use request.user in forms.py ?

The way I have done it is by creating a middleware in a file utils.

utils.py

from threading import current_thread
from django.utils.deprecation import MiddlewareMixin

_requests = {}

def get_current_request():
    t = current_thread()
    if t not in _requests:
        return None
    return _requests[t]


class RequestMiddleware(MiddlewareMixin):
    def process_request(self, request):
        _requests[current_thread()] = request

In settings include created middleware.

settings.py

MIDDLEWARE = [
...
...
"middleware_path.utils.RequestMiddleware",
...
]

In forms file the below structure is followed. Note:- This form will be accessible on for logged in user.

forms.py

from .utils import get_current_request

class OrderForm(forms.ModelForm):
    class Meta:
        ...

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        request = get_current_request()

That’s the solution I have used.

You can pass the value in to the form as a parameter of the constructor.

How do i accomplish that
Also, I want to use the current user data inside a method in the same modelForm

In your form, you need to save this parameter being passed.
example:

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

This removes the current user from the argument list (if provided) before passing those args to the parent class for creating the form.

Then, in your view, it’s my_form = MyForm(current_user=request.user) (with whatever other args may be needed such as request.POST).

Everywhere in your form you now have access to self.current_user which is request.user.

I have been trying the same thing
I m using forms.modelForm

Then when i go to use self.userr in the next method of the same modelForm
I get the error
Name “self” is not defined

And if i use the self in the method argument it gives :-
Missing required positional argument “self”

Please post the actual code you’re trying. It’s a lot easier to diagnose issues that way.

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

  def userdata():
        dta = self.current_user
        return dta
        

This code produces the error i mentioned

Your definition for userdata is incorrect. All functions defined as a method in a class receive self as the first parameter. See 9. Classes — Python 3.11.2 documentation for more details.

Yes, correct , but i have used self as a parameter as mentioned above , in my earlier reply
I get the error name ‘self’ not defined

No, it’s not in your function definition.

This line:

is wrong.

def userdata(self):
  x = self.current_user 

gives error as well

Please post the complete error. (Along with the complete Form class)

class buildday1(forms.ModelForm):
    


    class Meta:
        model = day1
        fields = ['d1from']
    def __init__(self, *args, **kwargs):
        self.current_user = kwargs.pop('current_user', None)
        super().__init__(*args, **kwargs)

    
   
    
    def placeName(self):
        x = self.current_user
        

        choice1 = []
        choice1.append(("None","None"))
        return choice1
        
        
    
    d1from = forms.ChoiceField( choices= placeName,required= False)

The error i have :::

TypeError at /itnry/buildday1
buildday1.placeName() missing 1 required positional argument: 'self'

What is the complete error? Please include the full traceback.

nvironment:


Request Method: GET
Request URL: http://127.0.0.1:8000/itnry/buildday1

Django Version: 4.1.4
Python Version: 3.11.1
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'places',
 'hotels',
 'itnry',
 'companyuser.apps.CompanyuserConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Template error:
In template C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\forms\templates\django\forms\p.html, error at line 9
   buildday1.placeName() missing 1 required positional argument: 'self'
   1 : {{ errors }}
   2 : {% if errors and not fields %}
   3 :   <p>{% for field in hidden_fields %}{{ field }}{% endfor %}</p>
   4 : {% endif %}
   5 : {% for field, errors in fields %}
   6 :   {{ errors }}
   7 :   <p{% with classes=field.css_classes %}{% if classes %} class="{{ classes }}"{% endif %}{% endwith %}>
   8 :     {% if field.label %}{{ field.label_tag }}{% endif %}
   9 :      {{ field }} 
   10 :     {% if field.help_text %}
   11 :       <span class="helptext">{{ field.help_text|safe }}</span>
   12 :     {% endif %}
   13 :     {% if forloop.last %}
   14 :       {% for field in hidden_fields %}{{ field }}{% endfor %}
   15 :     {% endif %}
   16 :   </p>
   17 : {% endfor %}
   18 : {% if not fields and not errors %}
   19 :   {% for field in hidden_fields %}{{ field }}{% endfor %}


Traceback (most recent call last):
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Users\Suhail\dev\py311\package\itnry\views.py", line 327, in bday1
    return render(request,  "itnry/buildday1.html", context=content)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\shortcuts.py", line 24, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\backends\django.py", line 62, in render
    return self.template.render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 175, in render
    return self._render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 167, in _render
    return self.nodelist.render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 966, in render_annotated
    return self.render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\loader_tags.py", line 157, in render
    return compiled_parent._render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 167, in _render
    return self.nodelist.render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 966, in render_annotated
    return self.render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\loader_tags.py", line 63, in render
    result = block.nodelist.render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 966, in render_annotated
    return self.render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\defaulttags.py", line 322, in render
    return nodelist.render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 966, in render_annotated
    return self.render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 1064, in render
    output = self.filter_expression.resolve(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 715, in resolve
    obj = self.var.resolve(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 847, in resolve
    value = self._resolve_lookup(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 914, in _resolve_lookup
    current = current()
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\forms\utils.py", line 84, in as_p
    return self.render(self.template_name_p)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\forms\utils.py", line 75, in render
    return mark_safe(renderer.render(template, context))
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\forms\renderers.py", line 29, in render
    return template.render(context, request=request).strip()
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\backends\django.py", line 62, in render
    return self.template.render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 175, in render
    return self._render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 167, in _render
    return self.nodelist.render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 966, in render_annotated
    return self.render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\defaulttags.py", line 238, in render
    nodelist.append(node.render_annotated(context))
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 966, in render_annotated
    return self.render(context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 1070, in render
    return render_value_in_context(output, context)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\template\base.py", line 1047, in render_value_in_context
    value = str(value)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\utils\html.py", line 419, in <lambda>
    klass.__str__ = lambda self: mark_safe(klass_str(self))
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\forms\boundfield.py", line 34, in __str__
    return self.as_widget()
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\forms\boundfield.py", line 94, in as_widget
    attrs = self.build_widget_attrs(attrs, widget)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\forms\boundfield.py", line 261, in build_widget_attrs
    widget.use_required_attribute(self.initial)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\forms\widgets.py", line 755, in use_required_attribute
    first_choice = next(iter(self.choices), None)
  File "C:\Users\Suhail\dev\py311\package\Lib\site-packages\django\forms\fields.py", line 849, in __iter__
    yield from self.choices_func()

Exception Type: TypeError at /itnry/buildday1
Exception Value: buildday1.placeName() missing 1 required positional argument: 'self'

Yea, I hate these types of errors.

Ok, my first guess is that:

should probably be:
d1from = forms.ChoiceField(choices=self.placeName, required=False)

The issue here is that you’re trying to reference the placeName method in this specific instance of the form, and not of the class itself, hence the need to specify that you want the instance-specific version of that method.

Tried this shows
“self” is not defined

Yep, my mistake. Sorry 'bout that.

I just checked some code that we use to do this.

We set the choices attribute on the field in the __init__ method after the super call.

So your field definition might be:
d1from = forms.ChoiceField(required= False)

Then, in __init__

    ...
    super().__init__(...)
    self.fields['d1from'].choices = self.placeName()

But, in the more general case, we try to look at the more “holistic” approach - look at what the complete underlying requirement is and try to evaluate the best approach for a given situation.

(It’s not clear to me from these examples exactly what you’re trying to achieve, so there’s the possibility that there’s an easier / better way to approach this.)

2 Likes

Alright that did the trick ,
Once again you are the boss

1 Like