Yuqing  Wei Yuqing Wei - 4 months ago 39
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
...etc.

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

I found that we can do it in the
template
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
template
? Cause I want to show them the different functions depends on their roles. For example I want to determine the role in the
example.js
which is included in the template:

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


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

<script>
var userType = '{{user.get_usertype}}';
</scirpt>


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!

Answer

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:

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

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.

Edit:

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:

html:

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

example.js:

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.