[Django]-HttpRequest instance add attribute dynamically in Django?

6👍

✅

HttpRequest is a class which inherits from object. In Python attributes can be set on objects at any time.

HttpRequest describes a HTTP request, which in its normal state does not include any data about the user. That is why the AuthenticationMiddleware adds user to the request.


__setitem__ is the method for setting indexed items on an object.

__setattr__ is the method for setting an attribute on an object, and is one of the methods implemented in object.


UPDATE
As @sayse said that is getting.

>>> class Test(object):
    pass

>>> test = Test()
>>> test.user #Try to access an unset attribute
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    test.user #Try to access an unset attribute
AttributeError: 'Test' object has no attribute 'user'
>>> test.user = 'user' #Set user attribute
>>> test.user #Try to access user
'user'

Leave a comment