[Answer]-Django and JQuery: Show form when prompted

1👍

You can check if a user is authenticated or not in your views. Set a variable True if user is authenticated and False if not.

# views.py

def my_view(request):
    if user.is_authenticated():
        auth_user = True
    else:
        auth_user = False
    # other code ...
    return render(... {'auth_user': auth_user, ...})

Then in your templates, render the form according to the variable auth_user.

{% if auth_user %}
    Display the form
{% else %}
    Display something else
{% endif %}
👤xyres

0👍

So, I think I found the correct solution, which is a combination of xyres’ answer and what I had already been trying to do. Here is some sample code for my final result:

<h1>{{ recipe.name }}</h1>

<ul>
    {% for item in recipe.line_items.all %}
        <li>
            <span id="item{{forloop.counter}}_hide">{{ item.full_name }}</span>
            {% if user_auth %}
            <form id="item{{forloop.counter}}_show"
{#                  action="{% url 'line_item:edit' %}"#}
                  class="hide-initial"
                  style="display: inline">
            {% csrf_token %}
                <input type="text" name="amount" size="2" value="{{ item.amount }}"/>
                <input type="text" name="unit"   size="4" value="{{ item.unit }}"/>
                <input type="text" name="name"   size="10" value="{{ item.ingredient_adjective }}"/>
                <input type="text" name="name"   size="10" value="{{ item.ingredient_name }}"/>
                <br>
                <input type="submit" name="submit" value="Submit">
                <input type="button" name="cancel" value="Cancel"
                       onclick="myFunction('item'+{{forloop.counter}}, true)">
            </form>
            <button id="item{{forloop.counter}}_hide" onclick="myFunction('item'+{{forloop.counter}})">Edit</button>
            {% endif %}
        </li>
    {% empty %}
        <li>No ingredients required!</li>
    {% endfor %}
    {% if user_auth %}
        <button>Add Ingredient</button>
    {% endif %}
</ul>

This template, accompanied by the following bit of JavaScript will allow the user to toggle the visibility of the form, individually, for each of the different ingredients.

$(".hide-initial").css( "display", "none" );

function myFunction(inp, reverse) {
    var show_elements = $("#" + inp + "_show");
    var hide_elements = $("#" + inp + "_hide");
    if(!reverse) {
        show_elements.css("display", "initial");
        hide_elements.css("display", "none");
    } else {
        hide_elements.css("display", "initial");
        show_elements.css("display", "none");
    }
}

Leave a comment