How to make form handler of checkbox, Python, Django - python

I have a problem: I want to make checkboxes of each line of table:
<form action="" method="post">
{% csrf_token %}
<table>
<thead>
<tr>
<th>cb</th>
<th width="150">first_col</th>
<th>sec_col</th>
<th width="150">third_col</th>
</tr>
</thead>
<tbody>
{% for i in list %}
<tr>
<td><input type="checkbox" name="choices" value="{{i.id}}"></td>
<td>{{ i.created_date}}</td>
<td> {{ host }}/{{i}}/ </td>
<td>{{i.number_of_clicks}}</td>
</tr>
{% endfor %}
</tbody>
</table>
<button type="submit" name="delete" class="button">Del</button>
</form>
And in the def I make next in order to check if it works:
if 'delete' in request.POST:
for item in request.POST.getlist('choices'):
print (item)
But it does not print anything... What do i do wrong? Or can you help me to write correct handler of checkboxes?

First you should check for request.method == 'POST' rather than for the submit button name in request.POST. Though, that shouldn't be the problem why you don't see anything. From what you posted I don't know what's not working but here's an example that shows how you could achive what you want. It assumes your template is in test.html:
# This is just a dummy definition for the type of items you have
# in your list in you use in the template
import collections
Foo = collections.namedtuple('Foo', ['id', 'created_date', 'number_of_clicks'])
def test(request):
# check if form data is posted
if request.method == 'POST':
# simply return a string that shows the IDs of selected items
return http.HttpResponse('<br />'.join(request.POST.getlist('choices')))
else:
items = [Foo(1,1,1),
Foo(2,2,2),
Foo(3,3,3)]
t = loader.get_template('test.html')
c = RequestContext(request, {
'list': items,
'host': 'me.com',
})
return http.HttpResponse(t.render(c))

Related

Problems changing the prefix of a formset in django

I have a question, what happens is that I have a formset and an empty_form (in the same HTML); I have them to do some calculations, for the empty_form I already managed to extract the ID and do operations but not for the formset, and that is that my main problem is that they have the different ID, for example for the formset is like this:
id_form-0-quantity
and for the empty_form it is:
id__form-1-quantity (one more underscore)
but with that different ID I have to make some changes in JS, which I don't want to do because I'm very new in JS and possibly messing up the code more. Is there a way to change the formset prefix to look like this: id__form-0-quantity?;
I used the following line:
formset = ParteFormSet(request.POST, request.FILES, prefix='__form')
But absolutely nothing happens
views
def create_Presupuestos(request):
extra_forms = 1
ParteFormSet = formset_factory(PresupuestosParteForm, extra=extra_forms, max_num=20)
presupuestosclientesform=PresupuestosClientesForm(request.POST or None)
presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None)
presupuestosparteform=PresupuestosParteForm(request.POST or None)
presupuestosmanoobraform=PresupuestosManoObraForm(request.POST or None)
presupuestospagosform=PresupuestosPagosForm(request.POST or None)
if request.method == 'POST':
formset = ParteFormSet(request.POST, request.FILES, prefix='__form')
if formset.is_valid():
presupuestosclientesform.save()
return redirect('presupuestos:index')
else:
formset = ParteFormSet()
return render(request,'Presupuestos/new-customer.html',{'presupuestosclientesform':presupuestosclientesform,'presupuestosvehiculosform':presupuestosvehiculosform,'presupuestosparteform':presupuestosparteform,'presupuestosmanoobraform':presupuestosmanoobraform,'presupuestospagosform':presupuestospagosform,'formset':formset})
HTML
<table class="table table-bordered table-nowrap align-middle" id="childTable1">
<thead class="table-info">
<tr>
<th scope="col">Quantity</th>
<th scope="col">Unit Price</th>
</thead>
<tbody>
{{ formset.management_form }}
{% for form in formset %}
<div class="part-form">
<tr>
<td>
{{form.quantity}}
<!-- <input type="text" name="parts_quantity" class="form-control input-new-customer-quantity" />-->
</td>
<td>
{{form.unit_price}}
<!-- <input type="text" name="parts_unit_price" class="form-control input-new-customer-unit-price" />-->
</td>
</tr>
</div>
{% endfor %}
</tbody>
</table>
<div class="part-form table-responsive" id="empty-row">
<table class="table table-bordered table-nowrap align-middle">
<tr>
<td>{{formset.empty_form.quantity}}</td>
<td>{{formset.empty_form.unit_price}}</td>
</tr>
</table>
</div>
You should also include the prefix in the case of a GET request, otherwise it will not prefix that form when you load the page for the first time:
def create_Presupuestos(request):
extra_forms = 1
ParteFormSet = formset_factory(PresupuestosParteForm, extra=extra_forms, max_num=20)
presupuestosclientesform=PresupuestosClientesForm(request.POST or None)
presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None)
presupuestosparteform=PresupuestosParteForm(request.POST or None)
presupuestosmanoobraform=PresupuestosManoObraForm(request.POST or None)
presupuestospagosform=PresupuestosPagosForm(request.POST or None)
if request.method == 'POST':
formset = ParteFormSet(request.POST, request.FILES, prefix='__form')
if formset.is_valid():
presupuestosclientesform.save()
return redirect('presupuestos:index')
else:
# prefix in case of a GET 🖟
formset = ParteFormSet(prefix='__form')
return render(request,'Presupuestos/new-customer.html',{'presupuestosclientesform':presupuestosclientesform,'presupuestosvehiculosform':presupuestosvehiculosform,'presupuestosparteform':presupuestosparteform,'presupuestosmanoobraform':presupuestosmanoobraform,'presupuestospagosform':presupuestospagosform,'formset':formset})

Django: Trying to click on a link and remove an assigned client

Good morning. I am having an issue trying to remove a client from an assigned bed. I created a one-item form called "RoomUpdate" that will allow a user to add a client to a bed that is empty via a dropdown through a ModelChoiceField.
When the bed is full, it does not allow the access to the drop down, instead, I have a link that states "remove client." What I want to happen is when I click that button, it assigns the default value of None to that bed in that room.
What's tricky, at least to my new-ish to Django mind, is how I do this through multiple tables. Having looked for multiple answers and tried different things, I know I've lost track of what I'm doing so I definitely could use some help.
models.py
class Room(models.Model):
room_id = models.AutoField(primary_key=True)
room_number = models.CharField(max_length=5)
shelter_id = models.ForeignKey(Shelter)
max_occupancy = models.CharField(max_length=3)
floor_location = models.CharField(max_length=3)
def __str__(self):
return self.room_number
class Bed(models.Model):
bed_id = models.AutoField(primary_key=True)
room_id = models.ForeignKey(Room, related_name='beds')
bed_size = models.ForeignKey(BedSize)
client_assigned = models.ForeignKey(Clients, null=True, blank=True, default=None)
forms.py
class RoomUpdate(forms.ModelForm):
client_assigned = forms.ModelChoiceField(queryset=Clients.objects.all(), required=False)
#def __init__(self, *args, **kwargs):
#super(RoomUpdate, self).__init__(*args, **kwargs)
#self.fields['client_assigned'].choices.insert(0, ('','---------' ) )
class Meta:
model = Room
fields = ( 'client_assigned', )
views.py
def room_update(request, pk, template_name='shelter/room_edit.html'):
rooms = get_object_or_404(Room, pk=pk)
form = RoomUpdate(request.POST or None, instance=rooms)
beds = Bed.objects.filter(room_id=pk)
if form.is_valid():
form.save()
return redirect('/shelter/')
return render(request, template_name, {'form': form, 'rooms': rooms, 'beds':beds,})
def remove_client(request, pk):
rooms = get_object_or_404(Room, pk=pk)
bed = Bed.objects.filter(room_id=pk)
form = RoomUpdate(request.POST)
template_fail = 'clients/invalid_permissions.html'
if request.method=='POST':
if form.is_valid():
bed.objects.update(client_assigned=None)
bed.save()
else:
return redirect(request, template_fail)
return render_to_response(request, {'rooms': rooms, 'bed': bed})
template
<form action="" method="POST">
{% csrf_token %}
<div class="room box-shadow">
<h4>Room {{ rooms.room_number }}</h4>
<table>
{% for i in rooms.beds.all %}
<tr>
<td>Bed ID: </td>
<td>{{i.bed_id }}</td>
</tr>
<tr>
<td>Bed Size: </td>
<td>{{i.bed_size }}</td>
</tr>
<tr>
<td valign="top">Client: </td>
<td>
{% if i.client_assigned %}
{{ i.client_assigned }}
<br \>
Remove Client
{% else %}
{{ form.client_assigned }}
{% endif %}
</td>
</tr>
<tr>
<td colspan="2">
<hr class="style-two" />
</td>
</tr>
{% endfor %}
<tr>
<td><input type="submit" value="Submit" /></td>
<td></td>
</tr>
</table>
</div>
</form>
I've been playing around with this a bit and making some sort of progress. If I change the url from the same as the edit, I get it to work in that it deletes from the table and redirects the user to a new page.
I would prefer it not redirect the user to a new page, but rather, update the page that's there.
Thoughts?
The new view looks like this:
def remove_client(request, pk, template_name='shelter/test.html'):
bed = Bed.objects.filter(bed_id=pk).update(client_assigned=None)
return render(request, template_name, { 'bed':bed })
Further diving into this, I found a solution I rather like and actually works in a way I wanted but couldn't figure out. Instead of focusing on the room, I realized that I needed to focus on the smaller container -- the bed -- and since it can move around, it would be the better choice.
Currently, this functionality allows me to move beds to different rooms, remove clients by selecting the '----' selector, and allows me to add clients.
So here is the answer I came up with:
forms.py
class RoomUpdate(forms.ModelForm):
bed_id = forms.CharField()
room_id = forms.ModelChoiceField(queryset=Room.objects.all())
bed_size = forms.ModelChoiceField(queryset=BedSize.objects.all(), required=False)
client_assigned = forms.ModelChoiceField(queryset=Clients.objects.all(), required=False)
class Meta:
model = Bed
fields = ('bed_id', 'client_assigned', 'room_id', 'bed_size' )
views.py
def room_update(request, pk, template_name='shelter/room_edit.html'):
beds = get_object_or_404(Bed,pk=pk)
form = RoomUpdate(request.POST or None, instance=beds)
if form.is_valid():
form.save()
return redirect('/shelter/')
return render(request, template_name, {'form': form, 'beds':beds,})
room_edit.html
<form action="" method="POST">{% csrf_token %}
<div class="room box-shadow">
<h4>Room </h4>
<table>
<tr>
<td>Room: </td>
<td>{{ form.room_id }}</td>
</tr>
<tr>
<td>Bed ID: </td>
<td>{{ form.bed_id }}</td>
</tr>
<tr>
<td>Bed Size: </td>
<td>{{ form.bed_size }}</td>
</tr>
<tr>
<td valign="top">Client: </td>
<td>{{ form.client_assigned }}</td>
</tr>
<tr>
<td colspan="2"><hr class="style-two" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td></td>
</tr>
</table>
</div>
</form>

Searching data in text file for output and convert to table dataframe

in advanced sorry if I have any mistake during reading my questions:
I'm working with Django and python for my website.
The process I need to read input from the user for searching the directory file that I want to read which is I take 2 input, input1, and input2.
I set the keyword in the variable if the keyword is matching I will print the next line.
THIS IS MY TEXT FILE
delay_index_time
775435
delay_index_time
456345
delay_index_time
4567867867868
delay_index_time
567867
Python Code In views.py
def SearchBox(request):
fullpath = ""
input1= request.GET.get('input1')
input2= request.GET.get('input2')
input_combine = str(input1).upper() + "_" + str(input2)
summary = '1A'
search_string = 'delay_index_time'
if input_Lot is None:
return render(request, 'Output.html')
else:
path = "D:/file/" + str(input_combine) + "/" + summary
with open(path) as input_data:
for line in input_data:
if search_string in line:
context = {
"output": (next(input_data))
}
return render(request, 'Output.html', context)
Template HTML
<form id = "lol" class="navbar-form navbar-left" role="search" method="GET" action="">
<div class="input-group">
<input style="left:260px; width:250px; top:-80px;" id="box1" name="input1" type="text" class="form-control" placeholder="Lot">
<input style="left:270px; top:-80px; width:250px;" id="box2" name="input2" type="text" class="form-control" placeholder="Operation">
<div style="left:540px; top:-101px;" class="input-group-btn">
<button id = "search_sub" value="Search" class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
{{ output|safe }}
{% endblock %}
My issue is it only print the first line of the output which is:
775435
But the other 3 output not display.
456345
4567867867868
567867
EXTRA QUESTION
How if i want the output display in table form in one column on my website.
NEW QUESTION
This is data in my text file.
I will display the string after I found 'id_' which is the id user.
Display the id user in one column.
Then, under id user got delay_index_time which I will display next line of the output.
But sometimes delay_index result will have more than one result.
I will zip it/combined in one table with 2 column.
It will display using a check box selection. if let's say user only want to view user id it will only display that. if the user ticks both of it in check box it will display both of it in the table.
For the check box, I have no idea on it. Sorry if I'm asking a lot of question :(
id_A1
delay_index_time
s_7754
s_7731
id_A2
delay_index_time
mrs_7745
id_A3
delay_index_time
s_77789
id_A4
delay_index_time
s_7752
This is my coding in views.py
context = {}
with open(path) as input_data:
for line in input_data:
if line.startswith('id_'):
if 'output' in context:
context['output'].append(line.lstrip('id_').rstrip())
if search_string in line:
if 'output1' in context:
context['output1'].append(next(input_data).lstrip('s_').rstrip())
context = {
'output': [(line.lstrip('id_').rstrip())],
'output1': [(next(input_data).lstrip('s_').rstrip())]
}
return render(request, 'Output.html', context)
This is my templates
<div class="container" style=" width:170px;">
<table style="" class="table table-bordered">
<thead class="success" >
<th class="active"><b>Visual ID</b></th>
{% for line in output1 %}
<tr class="success">
<td>{{ line }}</td>
</tr>
{% endfor %}
</thead>
<thead class="success" >
<th class="active"><b>Time Delay</b></th>
{% for line in output %}
<tr class="success">
<td>{{ line }}</td>
</tr>
{% endfor %}
</thead>
</table>
views.py
Templates
Try this, it works for me.
context = {}
with open(path) as input_data:
for line in input_data:
if search_string in line:
if 'output' in context:
context['output'].append(next(input_data))
else:
context = {'output': [(next(input_data))]}
return render(request, 'Output.html', context)
And to display output in a tabular form.
<table>
<tr>
<th>Output</th>
</tr>
{% for line in output %}
<tr>
<td>{{ line }}</td>
</tr>
{% endfor %}
</table>

Send table data from template to view.py in django

I am passing a list i.e data_code from view.py to a html file and from there i am printing the data of the table using for loop through the list. There is a editable column in the table <input> and i want to get those data after filled by user on my view.py. so anybody any idea how to do that??
I want to get all {{x.2}} in view.py. It is printing some default value but i want it again after it is being by user.
Here is the code:
<table class="table table-bordered datatable">
<thead class="table-head">
<tr>
<th>No</th>
<th>Code Point</th>
<th>Reference</th>
<th>Character</th>
<th>Text</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{% for x in data_code %}
<tr class="table-row">
<td>{{ forloop.counter }}</td>
<td><label>{{ x.0 }}</label></td>
<td><input id="codepoint_input" type="text" value={{x.2}} size=3 title="Text"></td>
<td><label> {{x.3}}</label></td>
<td>{{x.4}}</td>
</tr>
{% endfor %}
</tbody>
</table>
Edit:
Use dictionary type so that you can give each input box a unique name through the key, and use the corresponding value in value parm.
In view, you can use a for loop to go through the whole dictionary, and use the key to get the values from the template.
In your Template:
<form name = "yourForm" method="GET" action="/" class = "main">
{% for key, value in json.data_code%}
<td>
<input name = "{{ key }}" id="codepoint_input" type="text" value={{ value }} size=3 title="Text">
<input type="submit" id = "amountbtn" style="visibility:hidden;" >
</td>
{% endfor %}
</form>
In your views:
key1 = request.GET.get('key1')
....
The first task is get those entered values using jquery simply...
$(#codepoint_input).keypress(function(e) {
if(e.which == 13) {
// your custom code here.
var tablestring = $("#tableForm").serialize();
$.post( "/backend", tablestring );
}
});
Finally you can get the values in your view function...
def backend(request):
print(request.POST)

Using Flask and WTForms how can i have a table where some columns are inputs?

I'm struggling to see how this is done, and the documentation doesn't seem to help much.
I need to generate a table, the row size will be variable, but not dynamic (i know how much rows i need before generating the page).
For the sake of simplicity lets imagine a page where you grade n exams with an integer.
i tried this:
the form.
class InputInteger(Form):
grade = IntegerField('Grade')
the view
#decorator..
def grade():
form = InputInteger()
names = student_list
return render_template("grade.html", form=form, names=names)
the template
<table>
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
{% for name in names %}
<tr>
<td>
{{name}}
</td>
<td>
{{form.grade}}
</td>
</tr>
</table>
But how do i read back the inputed values?
How do i distinguish who's grade that belongs too?
Am fairly confused, i've read about FieldList(FormField(IntegerField)), but isn't that just one field with a list of integers?
What about the Table Widget, do i need that?
Please help.
For anyone looking at this now, the OP was correct to think about FieldLists and FormFields. Here is a solution:
forms.py:
class GradeForm(FlaskForm):
student = IntegerField('Student ID')
grade = IntegerField('Grade')
delete = BooleanField('Delete')
class GradeFormSet(FlaskForm):
gradeset = FieldList(FormField(GradeForm), min_entries=0)
view.py:
def grade():
# create a dict of student IDs and their initial grades (or None for now)
init_merits = [dict(student=s.id, grade=None) for s in myStudentTable.query.all()]
gradeform = GradeFormSet(gradeset=init_merits)
if form.validate_on_submit():
...
# meritforms.data['gradeset'] contains a list of dictionary values for further processing
# check 'delete' == True to handle deletion of that student from your table
...
return render_template('template.html', form=gradeform)
Template:
<table>
{% for merit in form.gradeset %}
<tr>
<td>{{ merit.placing(readonly=true) }} {{ merit.csrf_token }} {{ merit.hidden_tag() }}</td>
<td>{{ merit.grade }}</td>
<td>{{ merit.delete }}</td>
</tr>
{% endfor %}
</table>
<input type="submit" name="finish" value="Save">
<input type="submit" name="cancel" value="Cancel">
You're almost right. Put your table inside a html form and catch in a function where you can retrieve your input fields.
Here is an example:
<form action="/grade">
<table>
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
{% for name in names %}
<tr>
<td>{{name}}</td>
<td><input id='{{name}}' value='{{ form.grade }}'></td>
</tr>
</table>
</form>
And your Flask function:
#app.route('/grade', methods=['GET', 'POST'])
def grade():
if request.method == 'POST':
return 'Form posted.'
When you post your form to your function, you can access your input field by this way: request.form['inputfieldname'] and then you do your stuff. I hope my explanation is clear.

Categories

Resources