Reputation: 1239
I am currently designing a recipies website, using Django and JQuery. I have the ingredients and recipe instructions stored in the database, with appropriate Django views. Here is an example screenshot:
I would like to give the user the option to edit the ingredients of a recipe. When the user clicks on the "edit" button, I would like to replace the text to it's left, with a form pre-populated with the current ingredient components. Something like this:
What is the best way to add/remove these text input areas? Currently, I am using style elements display: none
and display: initial
to get the job done. Is there a better way?
Upvotes: 0
Views: 78
Reputation: 1239
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");
}
}
Upvotes: 0
Reputation: 21799
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 %}
Upvotes: 1