Yuqing  Wei Yuqing Wei - 3 months ago 20
Python Question

different roles in Django: show different content in web page

I'm using Django to develop an webapp, I created different roles of users, for example

CunstomerUser, GoodUser, Admin

Now I want to show them different things when they login. For example, when they open a popup, the
will see a textarea field for commenting and for the
he will see other things he can do.

I found that we can do it in the
level, like:

{% if request.user.is_superuser %}
.... superuser content
{% else %}
.... non-superuser content
{% endif %}

But how can I do in the javascript file which is used by this
? Cause I want to show them the different functions depends on their roles. For example I want to determine the role in the
which is included in the template:

<script type="text/javascript" src="example.js"></script>

The current solution that I found is to create a variable global javascript in the template so that all the javascipt files can use:

var userType = '{{user.get_usertype}}';

But is their a better way to do this? the variable global is not so good to use I think...maybe I used a dump pattern design. Any ideas? Thanks!


I might be wrong but you could still use django template syntax in javascript, because django template is evaluated before the page is loaded, so it still works by hiding/showing the portion that's relevant to the specific user:

{% if request.user.is_superuser %}
    var userType = 'superuser';
{% else %}
    var userType = 'normaluser';
{% endif %}

The above code block doesn't have to be global, it could happen anywhere within your template file. You will always get just one definition of userType in this case.


Well, the point of avoid global variables is because they might get changed by other functions so the values might messed up. However if you define pseudo-constants then you should be fine.

Javascript doesn't have constants but you could use any html with an id to achieve that:


<p style="display: none;" class="identity" id="{% if request.user.is_superuser %}superuser{% else %}normaluser{% endif %}"></p>


var user_role = $('p.identity').attr('id');

One caveat is that you need to load your example.js at the end of the template, otherwise it will load before the html loads, thus couldn't find the element.