How to add an attribute to request like the 'user' variable

Jango

I want to create a new variable which is always available like how the 'user' variable works.

Here is my myapp/context_processors.py

def patient_selected(request):

print(hasattr(request, 'patient_selected_id'))
print( 'patient_selected_id' in locals())
print( 'patient_selected_id' in globals())

if not hasattr(request, 'patient_selected_id'):
    request.patient_selected_id = 0

return {"patient_selected_id": 0}

The problem is, it always prints 'false'. It seems like I cannot add an attribute to the request, nor create a variable constantly available. BTW, I have added this context_processors.py to settings. Here is my setting:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
            'hrs.context_processors.patient_selected',
        ],
    },
},

]

EDIT: After reading source codes, it seems like the user variable is not actually created once and live forever. The Middleware and context_processor add a variable user for every request, and this 'user' is actually pulled from session.

My original design is: Once a patient is selected, all following pages will be about this patient. Thus, I would like to make this patient's id always available. Instead of pass this id all around, I want to save it(somewhere) once and always available until another patient is selected.

However now, considering the complexity of user variable, I may give up the fancy way. Simply put this id as a parameter in every request url should be easier.

Willem Van Onsem

Django does that with middleware [Django-doc]. In fact setting the .user attribute is done with middleware as well. Indeed, you can see this in the AuthenticationMiddleware [GitHub]:

class AuthenticationMiddleware(MiddlewareMixin):
    def process_request(self, request):
        assert hasattr(request, 'session'), (
            "The Django authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE%s setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'."
        ) % ("_CLASSES" if settings.MIDDLEWARE is None else "")
        request.user = SimpleLazyObject(lambda: get_user(request))

If you remove the 'django.contrib.auth.middleware.AuthenticationMiddleware' string from the MIDDLEWARE setting [Django-doc], then the request.user will no longer be set.

You can thus implement your own middleware. For example with:

# app/middleware.py

from django.utils.deprecation import MiddlewareMixin

class PatientSelectIdMiddleware(MiddlewareMixin):

    def process_request(self, request):
        if not hasattr(request, 'patient_selected_id'):
            request.patient_selected_id = 0

Next you need to add the 'app.PatientSelectIdMiddleware' middleware to the MIDDLEWARE setting.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Is it possible to add an attribute to a variable in python?

分類Dev

flutter: FadeInImage.assetNetwork: how to add request header like access token

分類Dev

Django UserCreationForm add request.user.pk?

分類Dev

How to give to a user ability like root with visudo?

分類Dev

How to set a JavaScript variable in attribute of a HTML tag

分類Dev

How to add an attribute with a hyphen in the name to a script element?

分類Dev

how to add one on name attribute with javascript?

分類Dev

How to add RectIntl Formatted message as html attribute

分類Dev

How to add custom attribute to customer export csv

分類Dev

I would like to add one day to a date and save it as a new variable

分類Dev

How to make If in array LIKE variable then do something

分類Dev

How to add style - like margin - to react component?

分類Dev

How do you detect if an attribute like password has changed in typeorm

分類Dev

How to request user login in models or views

分類Dev

How to detect that user is offline after an $http request

分類Dev

JS How to add variable into span

分類Dev

How to add a condition to a variable - GAMS

分類Dev

How to add a variable in javascript function

分類Dev

How to remove user commited with user from Pull request?

分類Dev

How to get an attribute from OpenSSL::X509::Request?

分類Dev

How to a variable can manage all client request

分類Dev

Webflux, How to intercept a request and add a new header

分類Dev

How to add attributes to a request in a scrapy contract

分類Dev

Round 3 Neither BindingResult nor plain target object for bean name 'user' available as request attribute

分類Dev

**Neither BindingResult nor plain target object for bean name 'user' available as request attribute**

分類Dev

How to make expressjs support batch request like facebook

分類Dev

Trying to add user inputted variable into already existing list in a different file?

分類Dev

How to create a particular profile based on user attribute in Django using signals

分類Dev

How to define globally a user input as variable

Related 関連記事

  1. 1

    Is it possible to add an attribute to a variable in python?

  2. 2

    flutter: FadeInImage.assetNetwork: how to add request header like access token

  3. 3

    Django UserCreationForm add request.user.pk?

  4. 4

    How to give to a user ability like root with visudo?

  5. 5

    How to set a JavaScript variable in attribute of a HTML tag

  6. 6

    How to add an attribute with a hyphen in the name to a script element?

  7. 7

    how to add one on name attribute with javascript?

  8. 8

    How to add RectIntl Formatted message as html attribute

  9. 9

    How to add custom attribute to customer export csv

  10. 10

    I would like to add one day to a date and save it as a new variable

  11. 11

    How to make If in array LIKE variable then do something

  12. 12

    How to add style - like margin - to react component?

  13. 13

    How do you detect if an attribute like password has changed in typeorm

  14. 14

    How to request user login in models or views

  15. 15

    How to detect that user is offline after an $http request

  16. 16

    JS How to add variable into span

  17. 17

    How to add a condition to a variable - GAMS

  18. 18

    How to add a variable in javascript function

  19. 19

    How to remove user commited with user from Pull request?

  20. 20

    How to get an attribute from OpenSSL::X509::Request?

  21. 21

    How to a variable can manage all client request

  22. 22

    Webflux, How to intercept a request and add a new header

  23. 23

    How to add attributes to a request in a scrapy contract

  24. 24

    Round 3 Neither BindingResult nor plain target object for bean name 'user' available as request attribute

  25. 25

    **Neither BindingResult nor plain target object for bean name 'user' available as request attribute**

  26. 26

    How to make expressjs support batch request like facebook

  27. 27

    Trying to add user inputted variable into already existing list in a different file?

  28. 28

    How to create a particular profile based on user attribute in Django using signals

  29. 29

    How to define globally a user input as variable

ホットタグ

アーカイブ