user972014
user972014

Reputation: 3856

Django - add context to request to be used by the view

Using Django I want to implement some middleware that will calculate some context that is to be used by the view itself.

For example, I have a middleware that looks at the request, and adds the user's permissions to the request, or some user configuration. The view looks at these permissions and decides how to handle the request using it.

This saves the need for multiple views (and multiple parts within the view) to query for this information.

I'm wondering what is the correct way to do that. One option is to just add request.user_permissions=... directly on the request. But is there some documented and expected way to do that?

Upvotes: 0

Views: 2800

Answers (3)

validname
validname

Reputation: 1526

I believe, since your middleware will calculate context, it should be implemented as context processor.

https://docs.djangoproject.com/en/3.1/ref/templates/api/#using-requestcontext https://docs.djangoproject.com/en/3.1/ref/templates/api/#writing-your-own-context-processors

Upvotes: 1

user1600649
user1600649

Reputation:

There's no real documented way to do that, but Middleware is the correct place to do it and just adding properties to the request object is also the correct way.

You can confirm this, because Django is already doing it:

So just pick whatever is the most convenient data structure for your use case and tack that on to the request object.

Upvotes: 3

user13769010
user13769010

Reputation:

This is not a perfect answer but at my experience I use this code. Every permission is saved in a boolean value which is true or false. You can access it in a html template like.

{% if request.user.is_admin %}
    "Your code here"
{% else %}
    "Your code here"
{% endif %}

and to send extra context you should create and pass an dicionary and pass it as as an argument to the render method from the view.
For eg:

def view(request, slug):
    context = {'administrator':True}
    blog_post = get_object_or_404(BlogPost, slug=slug)
    context['blog_post'] = blog_post

    return render(request, 'blog/detail_blog.html', context)

and access it like

{% if context.administrator %}
    "Your code here"
{% else %}
    "Your code here"
{% endif %}

Upvotes: 0

Related Questions