Web2py AJAX value - python

I have a list of Projects in my view and I would like to dynamically generate individual pages for each one.
My view:
{{for i in project_list:}}
<ul>
<input id="hello" type="hidden" value="{{response.write(i)}}" name="project_Name">
<li><a onclick="ajax('{{=URL('default', 'view_project')}}', ['project_Name'], 'target');">View Project</a></li>
</ul>
{{pass}}
My controller:
def view_project():
print request.vars.project_Name
return dict(name=request.vars.project_Name)
Essentially, I would like to identify each Project by its project_Name.
This is the current output from the controller:
['Customizable logistical service-desk ', 'Extended contextually-based prod
uctivity ', 'Face-to-face modular circuit ', 'Multi-tiered stable intranet
', 'Quality-focused coherent budgetary management ']
Why am I receiving an Array of all project names as output?
I just want to identify each project.
Any advice is appreciated!

The web2py ajax function sends to the server the value of the html element with the name attribute passed in the functions second parameter ("project_Name" in your case), but if there are more than one field with the same name, it will send the values of all of them.
So, you are creating with a loop many fields with the same name, and the ajax function is sending all the values to the server.
You can solve the problem appending a count variable to each field name (and its name on his onclick attribute):
{{count = 1}}
{{for i in project_list:}}
<ul>
<input id="hello" type="hidden" value="{{response.write(i)}}" name="project_Name{{=count}}">
<li><a onclick="ajax('{{=URL('default', 'view_project')}}', ['project_Name{{=count}}'], 'target');">View Project</a></li>
</ul>
{{count += 1}}
{{pass}}
Or use a more clean solution usin the JQuery ajax function

You have:
ajax('{{=URL('default', 'view_project')}}', ['project_Name'], 'target')
You have specified "project_Name" as the form input element from which to extract the value to post. However, there are multiple inputs on the page all with that same name. As a result, the Ajax function serializes all of their values into a single list and posts the whole list.
You could give each input a unique name, but there is a simpler solution. It appears you are using the hidden input elements merely to hold values to be sent by the Ajax function. There is no need for that -- instead, you can simply encode the values directly in the Ajax URL. So, get rid of the input elements and change your ajax call to:
ajax('{{=URL('default', 'view_project', vars=dict(project_name=i)}}', [], 'target')

Related

passing dictionary to view ,with multiple key:value pairs

def status_(request,id):
stages=['Vendor Quotation','Estimate Generation','Purchase Requsition','Purchase Order','Provision To Invoice','Reimbursement Invoice','Request Receipt#(PTI+RI+PO)','Receipt# Received(Updated PTI)','Request Sales Tax Invoice','Uploaded to Jazz Portal']
ctx={'invoice':Invoices.objects.get(pk=id),'stages':stages}
return render(request,"Invoices/status.html",ctx)
Hi I am trying to pass multiple objects of data for displaying to the template for displaying , I am creating a ctx dictionary with multiple 2 key value pairs ,second Key-value pair is array ,when i access this array in by using
{% for idx in range(0,len(ctx.get("stages")) %}
I get following parsing error
**Could not parse the remainder: '(0,len(ctx.get("stages"))' from 'range(0,len(ctx.get("stages"))'**
You can not make function calls in Django templates with parameters, hence the above wiull not work, but likely you do not need this anyway, you can simply enumerate with:
{% for stage in stages %}
{{ stage }}
{% endfor %}
If you really need to enumerate, then you can pass a range object through the context, but then probably a next problem pops up: you can not subscript with a variable either. It will require using a lot of extra template filters, making it very complicated. Templates are normally not used to implement business logic, therefore Django has a template engine that does not support complicated function calls, etc. to give the developer an incentive to move the business logic to the view.

Can I use a variable as index in for loop in python?

I have this for loop on my python template to fulfill an array of values:
labels: [{% for bftimes in dataBF.buffers.0.times %} "{{ bftimes }}", {% endfor %}]
I would like to know if I can use an int variable as an index instead writing it directly, as seen on the code above.
I need to use the index of the selected value of a dropdown:
//returns the index of the selected value
document.getElementById("buffer").selectedIndex
The question needs more context to help us understand your goal. It seems you are mixing python with javascript data structures.
My general recommendation is that you first prepare the python data structure to what you will need and then convert it to json. Looping within Django template language should be used only on simple cases.
If you use django>=2.1 you can use json-script template tag
{{ data|json_script:"my-data" }}
https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#json-script
If not, you can use
# views.py
import json
def foo(request):
dataBF = {"a": [{"c": [1,2,3,1,1]},{"d": [1,2,3,1,1]}]}
# here you can manipulate the data accordingly to what you need
data = json.dumps(dataBF)
return render(request, "index.html", context={"data": data})
On the template side
<script>
const datajs = {{ data | safe }};
</script>
The datajs is a javascript object that you can work with.
I've made an example that you can check https://repl.it/#IvanPereira/python-to-javascript-django-template
You can do this in 2 ways.
Store all values in a list, which JavaScript will consider as json array, and loop over using JavaScript itself. This way you won't be able to update records from server and all values that has to be looped over should be pre-fetched.
You can use AJAX call to pass the selected index from JavaScript and return the new array and update that in the template using JavaScript itself.

pyramid checkboxes

I'm just new to python and pyramid and I'm struggling with how to process the results of a form containing multiple checkboxes in Pyramid.
Here is an excerpt from my form:
<p tal:repeat="category categories">
<input type="checkbox" name="selectedcategories" value="${category.id}"> ${category.name}<br/>
</p>
And here is how I am currently trying to iterate through and process the results:
selectedcategories=request.params['selectedcategories']
for categoryid in selectedcategories:
category = DBSession.query(Category).filter_by(id=categoryid).one()
article.categories.append(category)
As you may have guessed, I'm only getting a maximum of one checkbox recognized no matter how many I select on the form. Django has an option to return the results as a list, but I can't seem to figure out how to do that with Pyramid.
request.params is a multidict. To retrieve multiple values, you can call its getall() method:
selectedcategories = request.params.getall("selectedcategories")

What is the format when I get data from multiple checkboxs? Can I get a list?

I have a Kind Tag with property tagName, and in a html, I code like this
{% for tag in tags%}
<input type="checkbox" name="tagName" value={{tag.tagName}}>{{tag.tagName}}
{% endfor%}
Now, In my python file, I try to do this:
tagNames = self.request.get('tagName')
I want a list that contain every choice user choose. But what I got seems not.
So.
how can I get a list of user choices using request.get()?
Is there any other ways? I am not familiar with django, I just import gae's template. Can I use gae's template to simplify
this question?
Thank you!
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict
Looks like QueryDict.getlist(key, default) will get you what you want.
ie. self.request.getlist('tagName')
Assuming you're using the webapp framework, instead of self.request.get(), use self.request.get_all('tagName'), which will return a list of values.

How to send multiple input field values with same name?

I have m2m field, lets say it have name 'relations', so i want to allow user to send as many relations as he wants. I add new input to html with javascript with same name, like so
<input type='text' name='relations' value='a' />
<input type='text' name='relations' value='b' />
in cleaned_data i receive only value of second input ('b'). How to receive both?
I don't know how to do that with Forms, but if you want to grab the values in the raw way, here's how I'd do:
relations = request.POST.getlist('relations')
You don't need to grab all the raw values, you can just get the specific data by using element name like this:
relations = request.form.getlist('relations')
That will return a list of values in the relations input.
this generate a list, you can manipulate in for
request.POST.getlist('relations')

Categories

Resources