0

I'm building a website (using python with django) in which you can access a users page and request something from them, but that functionality is only available for logged in users, whereas not logged in users can still see the page but not the form to send the requests. What would be the best practice for that:

-loading a different template when that view is requested directly on the server

or

-using javascript to change what is in the place where the 'request form' would be after verifying if user is logged in or not? thanks

Fabio
  • 3,015
  • 2
  • 29
  • 49

3 Answers3

3

The standard approach would be to use a simple if statement in your template.

{% if user.is_authenticated %}{% block form %}
{% else %} something else {% endif %}

To use JS you would have to make a request to the server to see if the user is logged in because to quote someone else on SO "There is no reliable way to do this without making a request to the server, since the session might have expired on the server side."

In general, I recommend conditionally showing content using JS when it doesn't require a server request unless you decided to move away from the standard Django "MVT" paradigm to something like "MVVM" in which case it's all JS.

Community
  • 1
  • 1
Charlie
  • 2,004
  • 6
  • 20
  • 40
1

You can use the same base html page, and conditionally render another template based on whether or not the user is logged in. The form could be held in that template. Example:

<body id="mySharedPage">
    ... Shared stuff ...
    {% if user.is_authenticated %}
        {% include "loggedInOnlyForm.html" %}
    {% endif %}
</body
wholevinski
  • 3,658
  • 17
  • 23
1

You can make use of user.is_authenticated in your template to only render the given portion of the template if the user is logged in.

{% if user.is_authenticated %}INSERT WHAT YOU WANT HERE{% endif %}
Christian Witts
  • 11,375
  • 1
  • 33
  • 46