How to store a table to database in Django 2.1? - html

I have a table inside html, and I need to save it into database using view and model and form. Here are some part of the code:
template.html
<form method="post" action="/images/save/" enctype="multipart/form-data">
{% csrf_token %}
<table class="table" border="1" id="tbl_posts">
<tbody id="tbl_posts_body">
{% for name, age in lines %}
{% with i=forloop.counter0 %}
{% with i|add:1|stringformat:"s" as i_id %}
{% with id="rec-"|add:i_id %}
<tr id={{id}}>
<td><span class="sn">{{ i|add:1 }}</span>.</td>
<td><INPUT type="text" name="txt1" value=""\></td>
<td><INPUT type="text" name="txt2" value=""\></td>
</tr>
{% endwith %}
{% endwith %}
{% endwith %}
{% endfor %}
</tbody>
</table>
<input type="submit" value="Submit">
</form>
model.py:
class Names(models.Model):
name= models.CharField(max_length=255)
age= models.IntegerField()
view.py:
def save_form(request):
template = "template.html"
context = {'txt1': "Name", 'txt2': 0}
if request.method == 'POST':
dname= request.POST.get("txt1")
dage= request.POST.get("txt2")
names1= Names(name=dname, age=dage)
names1.save()
return render(request, template, context)
Question:
So, it works perfectly, but the issue is that It saves only the last row. I think there is a way to enter the whole data. I need to enter all data in the table not only the last row. Can someone help me?
Update:
lines is a zip a combination of two lists, I read it from a file.

These two lines are the ones which get sent in a form.
<td><INPUT type="text" name="txt1" value=""\></td>
<td><INPUT type="text" name="txt2" value=""\></td>
However, you are using the same "names" to send the values for multiple rows.The result of that is that you will only get those values once with the current code you have in your view. You will want to give each of them a unique name (just do something like this:
<td><INPUT type="text" name="txt{{forloop.counter}}" value=""\></td>
and then iterate through them in your view.

Related

Is there any way to get form data from multiple forms in flask?

#app.route('/',methods = ['POST'])
def user_rating():
for i in form_value['Rating']:
print(request.form.get(str(i)))
return("Thank You")
I tried various methods but they are not working. Is there any way to iterate over form name and get their value
Above is the code I am working on and want to get data from multiple forms with a single button. But able to get only the first value from the form.
HTML code:
<tbody>
{% for record in records %}
<tr>
{% for col in colnames %}
<td>
{% if (col != 'poster_link') and ( col != 'Rating' ) %}
{{ record[col] }}
{% endif %}
<!--Movie Poster-->
{% if col == 'poster_link' %}
<img src={{ record[col] }} style="width:150px">
{% endif %}
<!--end of Movie Poster-->
<!--form Rating-->
{% if col == 'Rating' %}
**<form method="post" id="FORMID" action="{{url_for('user_rating')}}">
<input type="text" name= {{ record[col] }} placeholder="Give Rating 1 to 5" >
</form>**
{% endif %}
<!--end of form Rating-->
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
<button type="submit" form="FORMID" value="Submit">Submit</button>
Getting output like this
1
None
None
None
None
None
None
None
None
None
That is not possible because a user can only submit one form on a page. Whichever form is submitted is the one that gets read by your backend code. What you should do is either:
Use AJAX to make a request every time the input is changed, or
Only use one form
Based on your code, it appears that it will be easier to just use one form. So something like this would work:
<form method="post" id="FORMID" action="{{url_for('user_rating')}}">
<table>
<tbody>
{% for record in records %}
...
<input type="text" name= {{ record[col] }} placeholder="Give Rating 1 to 5" >
...
{% endfor %}
</tbody>
</table>
<button type="submit" form="FORMID" value="Submit">Submit</button>
</form>

Send an Array via a POST Message in Django

I have an array of checkboxes.
{% for groups in groupList %}
<tr>
<td id="checkboxes">
<input type="checkbox" name="check" id="check_{{groups.GroupID}}">
</td>
<tr>
{% endfor %}
I'd like to pass this array (preferably by ID so I can get the GroupID in the view) in a POST message. I'm not sure how to send this data though. Is there any way of attaching an array to a form parameter? Or any alternative solution?
{% for groups in groupList %}
<tr>
<td id="checkboxes">
<input type="checkbox" name="groups" id="check_{{groups.GroupID}}" value="{{groups.GroupID}}">
</td>
<tr>
{% endfor %}
In your views.py
groups=request.POST.getlist('groups')

Passing value from template to django view

I have a template in which I display some values. Now I want to be able to change that values. So I have an input field with the value "capacity.capacity". The user can now change this value in the input field and click on button "Change".
Now I want to process the newly entered value in my django view. How can I pass the new value to my view?
I tried to add the value in the url so that I can retrieve it in my view again.
Is it possible to add the new value to the url or is there a different/better way to do this?
<td>
<input type="number" name=new_capacity id="new_capacity" step="1" value= {{ capacity.capacity }}>
<button>
<span class="glyphicon glyphicon-edit"></span>
<a href="{% url 'change_capacity' item_id=capacity.pk new_capa=NEWVALUE %}"> Change
</button>
</td>
Update: Full code
I have two forms in this template and two submit buttons. Both buttons should redirect to different views. However it seems that always the same view is called.
{% block body %}
<form action="/producer/capacity/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Hinzufügen" />
</form>
<br/>
<br/>
<div class="container">
<table class="table">
<thead>
<tr>
<th>Maschine</th>
<th>Verfügbare Kapazität</th>
</tr>
</thead>
<tbody>
{% for capacity in capacity_list %}
<tr>
<td>{{ capacity.pk }}</td>
<td>
<form action="" method="post">{% csrf_token %}
<input type="number" name=new_capacity id="new_capacity" step="1" value="{{capacity.capacity}}" />
<input type="submit" value="Change"/>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
I think it's better to use POST method to make changes in the model data instead of using GET, so you can write a form like this in your template:
<form action="{% url my_app.views.my_capacity_view %}" method="post">{% csrf_token %}
<input type="number" name=new_capacity id="new_capacity" step="1" value="{{capacity.capacity}}" />
<input type="submit" value="Change" />
</form>
You can set the action form url in order to send the field to a custom view to modify the capacity value. Then, in the view, you can get the value and make the change, for example:
def my_capacity_view(request):
if request.method == 'POST':
new_capacity = request.POST.get('new_capacity ', '')
# set new value 'new_capacity' to the object
Set the url to point to the view
(r'^newcapacity', 'my_app.views.my_capacity_view'),
I hope this was useful

In Django, how to use a list from html checkboxes to loop through elements, and go to element specific page

I want to obtain a list from a HTML form with specific IDs in it:
search.html:
<form method='POST' action='/report/'>
{% for o in obj %}
<tbody>
<tr>
<td>{{o.sample}}</td>
<td><input type="checkbox" name="Samples" value="{{o.sample}}</td>
</tr>
</tbody>
{% endfor %}
<input type="submit" value="Submit">
</form>
This gives me a list of samples to my report view which takes me to /report/
in my URLs i have defined a regex so that it would be able to take me to a sample specific report URL:
url(r'^report/Sam\d{1,5}_\d{2}/$', views.report),
What I want is to be able to loop through this list sample IDs, so when I click the initial submit, it takes me to the first sample ID at:
localhost:8000/report/H1_1/
then I process and make a report for this sample, I submit and it takes me to the next sample ID in my list:
localhost:8000/report/H2_1/
etc.
I have been racking my brain on how to do this and the only thing I came up with was:
search.html:
{% for o in obj %}
<form method='POST' action='/report/{{o.sample}}'>
<tbody>
<tr>
<td>{{o.sample}}</td>
<td><input type="checkbox" name="Samples" value="{{o.sample}}</td>
</tr>
</tbody>
{% endfor %}
<input type="submit" value="Submit">
</form>
but I cant work how to get to the next sample in the sample specific html page form.
You probably want to close every form inside the loop, or you want a single form with all the entry, but what you have now is not so clean and could lead to errors.
Something like this:
{% for o in obj %}
<form method="POST" action="/report/{{o.sample}}">
<tbody>
<tr>
<td>{{o.sample}}</td>
<td><input type="checkbox" name="Samples" value="{{o.sample}}"></td>
</tr>
</tbody>
<input type="submit" value="Submit" label="Submit {{o.sample}}">
</form>
{% endfor %}
Or like this for a single form:
<form method="POST" action="/report/samples">
{% for o in obj %}
<tbody>
<tr>
<td>{{o.sample}}</td>
<td><input type="checkbox" name="Samples" value="{{o.sample}}"></td>
</tr>
</tbody>
{% endfor %}
<input type="submit" value="Submit" label="Submit">
</form>
But I think, based on what you wrote, that the 1st example better fits your needs.

Using html button to change status of data

I'm building an ecommerce site with django, and i wanted to create a button that would signal that an order had already been delivered.
I'm pretty sure you can acheive this with a checkbox, but i wanted to use a button, because it would be easier to click when using a tablet.
I want the button to also be "unclickable" in case someone accidentally clicked a button for a wrong order.
Do i need to make a form in the html? or is there an easier way to do it.
this is my html:
Order page
<table>
<tr>
<td>#</td>
<td>Name</td>
<td>Email</td>
<td>Phone</td>
<td>Order</td>
<td>Order Quantity</td>
<td>Delivered</td>
</tr>
{% for ord in orders %}
{% for food in ord.orderitem_set.all %}
<tr>
{% if forloop.counter == 1 %}
<td>{{ord.pk}}</td>
<td>{{ord.user.first_name}}</td>
<td>{{ord.user.email}}</td>
<td>{{ord.user.get_profile.phone}}</td>
{% else %}
<td colspan="4"></td>
{% endif %}
<td>{{food.name}}</td>
<td>{{food.quantity}}</td>
<td>{% if forloop.counter == 1 %} <button type="button">Delivered</button> {% endif %}</td>
</tr>
{% endfor %}
{% endfor %}
</table>
</body>
</html>
hmm, I think just putting a form around the button would be the "easier way" ^^
later if you wanted to, you could make it a spiffy javascript toggle using almost the same view code below maybe
e.g. around your buttons...
<form action="{% url show_orders %}" method="post">
<input type="hidden" name="order-id" value="{{ ord.pk }}"/>
<input type="hidden" name="action=" value="toggledelivery"/>
<button type="button">{% if not ord.is_delivered %}Not {% endif %}Delivered</button>
</form>
then in your view, something like...
def show_orders(request):
if request.method == "POST":
order_id = request.POST.get('order-id', None)
# TODO toggle the order here
return HttpResponseRedirect(back_to_the_order_admin_page)
else:
# ...show the admin page