django getlist() function - django

I have a tags generator for my blog site and every time I enter tags it generates a hidden html input, and it appends whenever I insert a tag like this example below.
<input type="hiiden" name="tags" value="<value of inserted tags>">
<input type="hiiden" name="tags" value="<value of inserted tags>">
<input type="hiiden" name="tags" value="<value of inserted tags>">
In my Django view I get all the tags from the form through request.POST.getlist("tags") and save it on database so the inserted tags is like this on database ['value1','value2','value3'] When I fetch the tags in the Django template through for loop to extract the strings from the arrayfield the output shows like this:
[ ' v a l u e 1 ' , ' v a l u e 2 ' , ' v a l u e 3 ' ] // one by one character output
the code works fine but the problem is it outputs character by character in the array including the brackets and the apostrophe and the commas. What i want to achieve is only the strings which are present in the array field
anyone knows what can be the solution for this? any suggestion and help is appreciated.

Related

Output nested list to xlsx using Django

I have a complex nested list of models that looks like this:
hierarchy_tree = ['0000', 'hierarchy' [['0000-22', 'hierarchy2', [['0000-33', 'hiearchy3', [['0000-44-4444', 'hiearchy4', [['0000-55-5555-55', 'hiearchy5', []]]]]]]]]]
I am able to easily display this in a template using dot notation - example:
{% for hierarchy in hierarchy_tree %}
<tr class="item" data-id="{{system.0}}" data-parent="">
<td>
{{hierarchy.0}}
</td>
<td>
{{hierarchy.1.genericname}}
</td>
Now I am trying to output this to an .xlsx file but I cannot figure out how to pass all of the levels of this list? How can I do the same thing that I did in the template to pass this list to excel?
I have tried the following which will return the 1st list but throws an error (ValueError at /post/1/export/hierarchy/ - cannot covert(my passed in list)to excel) for the sublists because of the way that they are nested I believe.
for r in hierarchy_tree:
ws.append(r)
I have also tried and failed repeatedly to access the sublists using other methods.
So bottom line I need to figure out how to access and pass the values for the sublists - any ideas or help will be greatly appreciated?
Thank you
Comment: ... is just 1 row in the list ...
Python print a instance of Type list in one line, surounding with [ ... ].
Your hierarchy_tree is of Type list of n lists.
Every n't list in hierarchy_tree starts with [ and ends with ].
You have to break your hierarchy_tree into row Data.
For instance:
def treeWalk(tree, level=0):
rData = [ '' for i in range(level)]
for item in tree:
if isinstance(item, list):
if len(rData) > level:
ws.append(rData)
level += 1
treeWalk(item, level)
return
rData.append(item)
treeWalk(hierarchy_tree)
Tested with Python:3.4.2 - openpyxl:2.4.1 - LibreOffice: 4.3.3.2

Splitting a string in the value attribute of Struts2 Iterator tag

I am stuck at one point in my project and I need some help. Below is my requirement.
I have a string(for ex: exampleString) which I am storing in session as follows:
request.getSession().setAttribute("exampleString",exampleString);
The exampleString will be like abc|def|ghi|jkl
Now in JSP I need to split it on "|" for using it in the Struts2 Iterator tag. For this I have written code as below:
<s:iterator var='item' value='#session.exampleString.split("|")'>
Remaining Code
</s:iterator>
Mow my problem is if I check the 'item' , the exampleString is not splitting up and the values that I am getting is a b c | d e f | g h i | j k l
I have also tried as follows:
<s:iterator var='item' value='#session.exampleString.split("\\|")'>
Remaining Code
</s:iterator>
The above code doesn't split the string at all.
I need to know where I am going wrong.
PS: This is my first post in this forum. Please let me know if I have done any mistakes while posting.
You need to escape \ as well so use:
<s:iterator var='item' value='#session.exampleString.split("\\\|")'>
Remaining Code
</s:iterator>

How can I count the number of attributes of an element in Selenium Python?

Having the following HTML code:
<span class="warning" id ="warning">WARNING:</span>
For an object accessible by XPAth:
.//*[#id='unlink']/table/tbody/tr[1]/td/span
How can one count its attributes (class, id) by means of Selenium WebDriver + Python 2.7, without actually knowing their names?
I'm expecting something like count = 2.
Got it! This should work for div, span, img, p and many other basic elements.
element = driver.find_element_by_xpath(xpath) #Locate the element.
outerHTML = element.get_attribute("outerHTML") #Get its HTML
innerHTML = element.get_attribute("innerHTML") #See where its inner content starts
if len(innerHTML) > 0: # Let's make this work for input as well
innerHTML = innerHTML.strip() # Strip whitespace around inner content
toTrim = outerHTML.index(innerHTML) # Get the index of the first part, before the inner content
# In case of moste elements, this is what we care about
rightString = outerHTML[:toTrim]
else:
# We seem to have something like <input class="bla" name="blabla"> which is good
rightString = outerHTML
# Ie: <span class="something" id="somethingelse">
strippedString = rightString.strip() # Remove whitespace, if any
rightTrimmedString = strippedString.rstrip('<>') #
leftTrimmedString = rightTrimmedString.lstrip('</>') # Remove the <, >, /, chars.
rawAttributeArray = leftTrimmedString.split(' ') # Create an array of:
# [span, id = "something", class="somethingelse"]
curatedAttributeArray = [] # This is where we put the good values
iterations = len(rawAttributeArray)
for x in range(iterations):
if "=" in rawAttributeArray[x]: #We want the attribute="..." pairs
curatedAttributeArray.append(rawAttributeArray[x]) # and add them to a list
numberOfAttributes = len(curatedAttributeArray) #Let's see what we got
print numberOfAttributes # There we go
I hope this helps.
Thanks,
R.
P.S. This could be further enhanced, like stripping whitespace together with <, > or /.
It's not going to be easy.
Every element has a series of implicit attributes as well as the ones explicitly defined (for example selected, disabled, etc). As a result the only way I can think to do it would be to get a reference to the parent and then use a JavaScript executor to get the innerHTML:
document.getElementById('{ID of element}').innerHTML
You would then have to parse what is returned by innerHTML to extract out individual elements and then once you have isolated the element that you are interested in you would again have to parse that element to extract out a list of attributes.

re pulls data from one tag and not the other

I am trying to get a program to work that parses html like tags- it's for a TREC collection. I don't program often, except for databases and I am getting stuck on syntax. Here's my current code:
parseTREC ('LA010189.txt')
#Following Code-re P worked in Python
def parseTREC (atext):
atext=open(atext, "r")
filePath= "testLA.txt"
docID= []
docTXT=[]
p = re.compile ('<DOCNO>(.*?)</DOCNO>', re.IGNORECASE)
m= re.compile ('<P>(.*?)</P>', re.IGNORECASE)
for aline in atext:
values=str(aline)
if p.findall(values):
docID.append(p.findall(values))
if m.findall(values):
docID.append(p.findall(values))
print docID
atext.close()
the p re pulled the DOCNO as it was supposed. The m re though would not pull data and would print an empty list. I pretty sure that there are white spaces and also a new line. I tried the re.M and that did not help pull the data from the other lines. Ideally I would like to get to the point to where I store in a dictionary {DOCNO, Count}. Count would be determined by summing up every word that is in the P tags and also in a list []. I would appreciate any suggestions or advice.
You can try removing all the line breaks from the file if you think that is impacting your regex results. Also, make sure you don't have nested <P> tags because your regex may not match as expected. For example:
<p>
<p>
<p>here's some data</p>
And some more data.
</p>
And even more data.
</p>
will capture this section because of the "?":
<p>
<p>here's some data</p>
And some more data.
Also, is this a typo:
if p.findall(values):
docID.append(p.findall(values))
if m.findall(values):
docID.append(p.findall(values))
should that be:
docID.append(m.findall(values))
ont the last line?
Add the re.DOTALL flag like so:
m= re.compile ('<P>(.*?)</P>',
re.IGNORECASE | re.DOTALL)
You may want to add this to the other regex as well.
from xml.dom.minidom import *
import re
def parseTREC2 (atext):
fc = open(atext,'r').read()
fc = '<DOCS>\n' + fc + '\n</DOCS>'
dom = parseString(fc)
w_re = re.compile('[a-z]+',re.IGNORECASE)
doc_nodes = dom.getElementsByTagName('DOC')
for doc_node in doc_nodes:
docno = doc_node.getElementsByTagName('DOCNO')[0].firstChild.data
cnt = 1
for p_node in doc_node.getElementsByTagName('P'):
p = p_node.firstChild.data
words = w_re.findall(p)
print "\t".join([docno,str(cnt),p])
print words
cnt += 1
parseTREC2('LA010189.txt')
The code adds tags to the front of the document because there is no parent tag. The program then retrieves the information through the xml parser.

How to see if a Django QueryDict key matches a pattern

I'm working on a site with a list-type view (shopping cart) where each item has a select drop-down widget to change shipping type. The resulting HTML, created by a for loop such that 'item_id_foo' changes on each cycle, looks like:
<select name='item_id_foo'>
<option value='bar1'>bar1</option>
...
<input type='submit' name='submit' value='Change'/>
</select>
As a result, by request.POST.copy has a key/value like {'item_id_foo':'bar1'}. My question is how to find keys that look like 'item_id_foo', 'item_id_bar', etc. Methods like "getitem", "get" or "contains" assume you know what the full key looks like, and I only know the pattern. How do I match for a pattern on a key?
Thank you,
bkev
Update: Example values for the select would be like:
'item_id_1', 'item_id_2', 'item_id_3'...matching the id of the item in the cart that needs to be edited (each has its own shipping method and fee).
Why not loop through the entire list and then do regex on each item's name? QueryDict.lists() or QueryDict.values() allows you to get all of it and then loop through that.
QueryDict.lists()
Like items(), except it includes all values, as a list, for each member of the dictionary.
For example:
>>> q = QueryDict('a=1&a=2&a=3')
>>> q.lists()
[(u'a', [u'1', u'2', u'3'])]
Link: http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict
Just iterate over the keys and keep those you want
>>> post = {'item_id_1': 1, 'item_id_2': 2, 'item_id_3': 3, 'noitem': 0}
>>> dict([(k, v) for k, v in post.items() if k[:8] == 'item_id_'])
{'item_id_3': 3, 'item_id_2': 2, 'item_id_1': 1}