use request.POST without knowing the name and number of inputs - django

Is there a way that become aware of name and value of inputs in request.POST?
I know i can access the value of inputs by knowing name of them like this:
name = request.POST['inputName']
but if i don't know how many inputs and with what names they are, what can i do? is there a way to loop through request.POST?
(i create my html with xsl, and because i'm creating html by parsing xml file, the number and nmame of inputs are variable. so i have to use this way)
really thanks for your help :)

The default iterator of Python dictionaries returns keys - what this means is that when you loop through a dictionary, it will return each key. Since request.POST is a "dict like" object, it works:
for i in request.POST:
print 'I have been passed the following keys: ',i
You can also do:
print 'The total number of keys in my POST request: ', len(request.POST.keys())

Try to just foreach them.
Example:
foreach(request.POST as item){
print item;
}

Related

Passing multiple values per key into template via ajax

I'm wanting to pass information relating to orders into my template via an ajax call. The problem is that that I've got more than two values that I want to pass in.
Key: Email address
Values that pertain to each key that I want to pass in:
Invoice Date
Name
Phone number
I'm wondering what the best way to do this is. Does the dictionary value need to be a list?
eg.
order_dict[order.email] = ['order.invoice_date', 'order.name', 'order.phone']
If the dictionary value does need to be a list, how would I iterate over it in my template?
Thanks for your help!

is it possible to form a list of keys from dictionary values? if not, is there an easier method to solve this?

The question is here as I can't upload images yet. Basically I've tried to do some code, but I got stuck :/
I'm not sure if I can call dictionary keys by value? I heard somewhere that I can't, but I need to form a list of ([key,key,key...], common value).
This was what I coded so far, is my approach correct?
import collections
def meh(n):
c=n.split()
count= collections.Counter(c)
# l=sorted(zip(*count)[1])
for k, value in count.iteritems():
return k, value
# if v = max(list(v)):
# return sorted(list(k)), max(v)
The comment hashes are because I tried different methods which also didn't work out for me ><"
If i understand you correctly you want to get a list of all the keys in a dictionary. To do this you can use
myarray = dictionary.keys()
myarray will then be a list of all the keys in the dictionary.

Django pass CommaSeparated values to GET paramater

We know that django has CommaSeperated model field. But how can we pass commaSeparated string to Django GET parameter.
Whenever i try to pass something like below as GET parameter:
1,2,3,4
I receive using below code in django view
request.GET.get('productids','')
It ends up like below in django view.
'1,2,3,4'
Its ends up adding quotes around the array.
Please any Django experts help me with this issue.
You can use getlist
param_list = request.GET.getlist('productids')
If you're passing it as a single parameter then you can construct it
param_list = [int(x) for x in request.GET.get('productids', '').split(',')]
Django converts GET and POST params to string (or unicode). That means, if you're sending a list (array) as a GET param, you'll end up getting a string at the backend.
However, you can convert the string back to array. Maybe like this:
product_ids = request.GET.get('productids', '')
ids_array = list(product_ids.replace(',', '')) # remove comma, and make list
The ids_array would look like this - ['1', '2', '3'].
Update:
One thing worth noting is the ids in ids_array are strings, not integers (thanks to Alasdair who pointed this out in the comments below). If you need integers, see the answer by Sayse.

Django - Query results as 'associative' dict?

I was wondering if there was any handy helpers in Django which would return the results of a query into a more 'usuable' format so I don't have to iterate through them in my view.
I have a query like this:
self.filter(key__in=keys).values('key','value')
What I want to end up is an object which looks like
{'some_key':'some value', 'some_other_key':'some_other_value'}
So in my model I could do something like this:
settings = Setting.objects.get_keys(['some_setting','some_other_setting'])
print settings.some_setting # returns 'some value'
Where 'get_keys' is a manager function which runs the above filter query. Any idea how I might do this? I wouldn't be opposed to iterating through the results in the Settings Manager because I could store them for later... I couldn't quite figure our how to create a 'global' model variable though.
Any help would be greatly appreciated!
If you use values_list rather than values, it will return a set of two-tuples, which you can then pass to dict() to create a dictionary:
return dict(self.filter(key__in=keys).values_list('key','value'))
I think what you're looking for is: http://docs.djangoproject.com/en/stable/ref/models/querysets/#in-bulk
This function takes a list of primary keys and return a dictionary of the models mapped to the keys. It sounds like this is exactly what you want?

How to get a list of queryset and make custom filter in Django

I have some codes like this:
cats = Category.objects.filter(is_featured=True)
for cat in cats:
entries = Entry.objects.filter(score>=10, category=cat).order_by("-pub_date")[:10]
But, the results just show the last item of cats and also have problems with where ">=" in filter. Help me solve these problems. Thanks so much!
You may want to start by reading the django docs on this subject. However, just to get you started, the filter() method is just like any other method, in that it only takes arguments and keyword args, not expressions. So, you can't say foo <= bar, just foo=bar. Django gets around this limitation by allowing keyword names to indicate the relationship to the value you pass in. In your case, you would want to use:
Entry.objects.filter(score__gte=10)
The __gte appended to the field name indicates the comparison to be performed (score >= 10).
Your not appending to entries on each iteration of the for loop, therefore you only get the results of the last category. Try this:
entries = Entry.objects.filter(score__gte=10, category__is_featured=True).order_by("-pub_date")[:10]