Django: Prefill forms with database entries from inside a loop - python

I want to prefill a form with already existing database entries but can't access the correct ones.
A user can create a task and pass information on when creating it. When he wants to update it later, the already saved information should be used to prefill the form.
My problem is, that I'm inside a for-loop and it seems that I can't access the elements of the loop.
Here is what I'm doing:
I'm in a template inside a for-loop. The loop lists all tasks with an update button for every task. This button calls a form via the bootstrap data-target. Here's an example:
{% for task in tasks %}
<button class="btn-primary btn-block btn-lg" data-toggle="modal" data-target="#updateTask">Update Task</button> {% endfor %}
In my upcoming form I can't use the variables from the task element. For example the task.taskname. However, I can use all other variables like the user.first_name which exists outside the loop.
<div class="modal-body">
<form method="POST" action="{% url 'update_task' %}">
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6">
<label for="name" class="col-form-label">Task:</label>
<input type="text" id="taskID" name="task" class="form-control" value="{{ user.first_name }}" required> -> this works
<input type="text" id="taskID2" name="task2" class="form-control" value="{{ task.taskname }}" required> -> this doesn't
</div>
<input type="submit" value="Send" class="btn btn-block custom-button">
</div>
I know I could do this with opening a completely new page but I want to try to use the data-target calling my view instead of calling the view directly.
Is there any way to pass my currently looped element to the form?
Thanks in advance!
Pascal

Related

HTML Jinja2 disabling submit button in specific situation

I am having problem with setting up logic for if statement in HTML template with Jinja.
What should I input in place of ??? in the below code?
I don't want the user to be able to post empty field, therefore, I have decided to disable the submit button while the textarea is empty (e.g.: it has different css style with the form__submit__disabled class).
I have tried inputting in the ??? place content, entry, form__textarea, but it doesn't work.
<form class="form" action="/" method="POST">
<p class="form__input">
<textarea name="content" id="entry" class="form__textarea" aria-label="Entry contents" placeholder="Type here..."></textarea>
</p>
{% if ??? is none %}
<button type="submit" class="form__submit__disabled" disabled>Add entry</button>
{% else %}
<button type="submit" class="form__submit">Add entry</button>
{% endif %}
</form>
A better idea, for this requirement would be to use the required attribute of the textarea, and let the browser do the job of warning the end user that this field should be filled in before submitting.
<form class="form" action="/" method="POST">
<p class="form__input">
<textarea name="content"
id="entry"
class="form__textarea"
aria-label="Entry contents"
placeholder="Type here..."
required></textarea>
</p>
<button type="submit"
class="form__submit">
Add entry
</button>
</form>

Mutliple buttons on one html page returning the same function- flask python

For a changing quantity in a cart.html page I have 3 seperate buttons for remove, increase and decrease the quantity. However, every time I press a button it only runs the increase function even though they all have different urls? enter code here
<td class="action" >
<form class="form" action="{{ url_for('increaseQuantity') }}" method="post">
<button class="ti-plus" value="{{ cart.Products.productID }}" name ="productID" ></button>
</form>
</td>
<td class="qty" data-title="Qty"><!-- Input Order -->
<div class="input-group">
<input type="text" class="input-number" value="{{ cart.Cart.quantity }}">
</div>
</td>
<td class="action" >
<form class="form" action="{{ url_for('minusQuantity') }}" method="post">
<button class="ti-minus" value="{{ cart.Products.productID }}" name ="productID" ></button>
</form>
</td>
<td class="action" data-title="Remove">
<form class="form" action="{{ url_for('removeFromCart') }}" method="post">
<button class="ti-trash remove-icon" value="{{ cart.Products.productID }}" name ="productID" ></button>
</form>
try changing name attribute on your buttons they are all having same name.
This HTML snippet is not enough to help you. Try looking at the generated code using you browser's tools, or add the URL dictionnary.
Also, you need to submit a form, with an input/button of the "submit" type. Their absence may create errors.
From https://www.w3schools.com/tags/tag_button.asp :
Tip: Always specify the type attribute for a element, to tell browsers what type of button it is.

How to add display dropdown fields in Django

I'm trying to add a category field to my blog posts model in Django. When I make a post with the admin panel it shows the choices in a drop down list, however I wish to display choices in html.
Here is the form in my HTML file:
<div class="container">
<div class="row">
<div class="col-lg-7 offset-lg-1">
<form class="create-form" method="POST" enctype="multipart/form-data">{% csrf_token %}
<!-- title -->
<div class="form-group">
<label for="id_title">Title</label>
<input class="form-control" type="text" name="title" id="id_title" placeholder="Title" required autofocus>
</div>
<!-- Body -->
<div class="form-group">
<label for="id_body">Content</label>
<textarea class="form-control" rows="10" type="text" name="body" id="id_body" placeholder="Put the description of your post here..." required></textarea>
</div>
<div class="form-group">
<label for="id_category">Category</label>
<select class="form-control" name="category" id="id_category" required></select>
</div>
<!-- Image -->
<div class="form-group">
<label for="id_image">Image</label>
<input type="file" name="image" id="id_image" accept="image/*" required>
</div>
I also asked these types of questions about Django in StackOverflow. However, it is really hard to explain your questions as a newbie to experienced people so I will not just answer your question but also I want to show you the path to do it.
I think there are multiple parts to your question. It is not just to create a dropdown list with choices in HTML but also, you want to pass the data from your blog posts model in Django.
Firstly, let's say that the name of the HTML file is posts.html. In posts.html, to create a dropdown in an HTML is like this; (assume that your categories are zero, one and two and you can see these on dropdown list in the admin panel)
<select name="post_categories" class="filter-selectbox">
<option value="zero">"Zero"</option>
<option value="one">"One"</option>
<option value="two">"Two"</option></select>
However, if you want to create a dropdown list using your model's field, you should do similar like this: (I assumed that you can be able to create a dropdown list with your post model's field named category.)
<select name="post_categories" class="filter-selectbox">
{% for post in posts %}
<option value="{{ post.category }}">{{ post.category }}</option>
{% endfor %} </select>
So now you can pass and use the object to HTML and can be able to use its fields.
However, I assumed that you can be able to pass objects to the template. If you do not know how, there is another question that how to pass data to an HTML file? You should search more about "passing objects to template".
In views.py, when you render the template, you can be able to pass parameters or objects to use them in your template. Please look at this for that: Django: Passing object from template to views
So in your case, it should be something like this;
def get_posts(request):
posts = Post.objects.all() # In this case, I assume that I can reach category as post.category in the template
context = {"posts": posts}
return render(request, "posts.html", context)
I hope for a newbie in Django, I could explain it as simple. Keep learning.
Good Luck!

Django form validation on clicking Next instead of Submit

I have this HTML page in which I have 2 forms. Django is not checking the form validation for the first form. I want it to check form validation for the first form.
This is the Html Code
<form method="post" id="msform">
{% csrf_token %}
<!-- progressbar -->
<ul id="progressbar">
<li class="active" id="conf"><strong>Configuration</strong></li>
<li id="auth"><strong>Authentication</strong></li>
</ul>
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
</div> <br> <!-- fieldsets -->
<fieldset>
<div class="form-card">
<div class="row">
<div class="col-7">
<h2 class="fs-title">Cluster Configuration</h2>
</div>
<div class="col-5">
<h2 class="steps">Step 1 - 2</h2>
</div>
</div>
{{ form1|crispy }}
</div> <input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<fieldset>
<div class="form-card">
<div class="row">
<div class="col-7">
<h2 class="fs-title">Authentication</h2>
</div>
<div class="col-5">
<h2 class="steps">Step 2 - 2</h2>
</div>
</div>
{{ form2|crispy }}
</div><button type="submit" class="btn btn-primary" >Next</button>
</fieldset>
</form>
If I use submit button instead of next for the first form then neither the second form opens nor the form is submitted (i.e. nothing is happening).
So I think the issue might be because you have over arching form tag, and two forms sent inside it from your view function:
What you have right now is this:
<form>
<fieldset>
<! –– Your Code ––>
{{ form1|crispy }}
</div> <input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<fieldset>
<! –– Your Code ––>
{{ form2|crispy }}
</div><button type="submit" class="btn btn-primary" >Next</button>
</fieldset>
</form>
As you can see from the above simplification of your original post, you have two forms templated inside one form tag. Thus when you hit either of the the submit button both of them gets sent.
If I am not mistaken, I believe what you might want is something along the lines of this:
<form name="form1" id="form1">
<fieldset>
<! –– Your Code ––>
{{ form1|crispy }}
</div> <input type="button" name="form1" class="next action-button" value="Next1" />
</fieldset>
</form>
<form name="form2" id="form2">
<fieldset>
<! –– Your Code ––>
{{ form1|crispy }}
</div> <input type="button" name="form2" class="next action-button" value="Next2" />
</fieldset>
</form>
Take note of the fact that I have changed your button names, as well as added ids and names to each form, you might also want to add ids as well as unique values to your buttons as well. This would help you build if conditions to determine which form has been submitted and so on, in your view function
Here is a link that describe how to handle this in more depth.
Which is all nice and dandy, but the conclusion of that linked page is this:
Let me know if it helps, feel free to ask more if you do not understand/the changes does not work

How to get checkbox values in django application

I am trying to use a check box control in a simple django application. Code Logic seems to be fine, But I am getting an empty fruit list ([None, None]). I don't know why it's not working, Can anybody point out the mistake. Thanks in advance
index.html
<div class="form-check">
<input class="form-check-input" type="checkbox" value="Apple" id="apple">
<label class="form-check-label" for="apple">Apple</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="Mango" id="mango">
<label class="form-check-label" for="mango">Mango</label>
</div>
view.py
if request.method == 'POST':
fruit = []
fruit.append(request.POST.get('apple'))
fruit.append(request.POST.get('mango'))
As Daniel mentioned, you have to add a name attribute to form elements, so they are submitted to the server.
index.html
<form method="post">
{% csrf_token %}
<div class="form-check">
<input class="form-check-input" type="checkbox" value="Apple" id="apple" name="fruits">
<label class="form-check-label" for="apple">Apple</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="Mango" id="mango" name="fruits">
<label class="form-check-label" for="mango">Mango</label>
</div>
<button type="submit">Submit</button>
</form>
That way, you can get a list of fruits in your view:
views.py
if request.method == 'POST':
fruits = request.POST.getlist('fruits')
The fruits variable would be a list of check inputs. E.g.:
['Apple', 'Mango']
input elements need a name attribute, otherwise the browser does not send any data.

Categories

Resources