QueryDict has list, but actualy show string [duplicate] - django

Using django 1.8, I'm observing something strange.
Here is my javascript:
function form_submit(){
var form = $('#form1_id');
request = $.post($(this).attr('action'), form.serialize(), function(response){
if(response.indexOf('Success') >= 0){
alert(response);
}
},'text')
.fail(function() {
alert("Failed to save!");
});
return false;
}
and here are the parameters displayed in views.py
print request.POST
<QueryDict: {u'form_4606-name': [u''], u'form_4606-parents': [u'4603', u'2231', u'2234']}>
but I cannot extract the parents:
print request.POST['form_4606-parents']
2234
Why is it just giving me the last value?
I think there is something wrong with the serialization, but I just cannot figure out how to resolve this.

From here
This is a feature, not a bug. If you want a list of values for a key, use the following:
values = request.POST.getlist('key')
And this should help retrieving list items from request.POST in django/python

The function below converts a QueryDict object to a python dictionary. It's a slight modification of Django's QueryDict.dict() method. But unlike that method, it keeps lists that have two or more items as lists.
def querydict_to_dict(query_dict):
data = {}
for key in query_dict.keys():
v = query_dict.getlist(key)
if len(v) == 1:
v = v[0]
data[key] = v
return data
Usage:
data = querydict_to_dict(request.POST)
# Or
data = querydict_to_dict(request.GET)

You can use getlist method
data = request.POST.getlist('form_4606-parentspass_id','')

The simplest way
{**request.GET}
{**request.POST}
or, if you use djangorestframework
{**request.query_params}

Related

How to do a sequential query in a flask database

as said in the title I'm supposed to query a database(SQLAlchemy) in a sequential manner: most of the data come from a checkbox in the HTML, I know that I can just do all the queries in one line but, here the problem: I've to query only the value that are going to be True, and obviously I can't foresee how many. So I'm asking if any of you knows a method to do so correctly, moreover I didn't find anything about nulling the booleans that are not True. Thanks for helping me!
Here is the code, I'm sure that there are not problem in the Database or in the HTML, but it just about how to do so.
if request.method == 'POST':
post_city = str(request.form['city'])
post_nation = str(request.form['nation'])
post_tools = request.form.get('fitness_tools')
post_pub = request.form.get('pub_presence')
post_games = request.form.get('games')
post_crowded = request.form.get('crowded')
post_fountain = request.form.get('fountain')
list_of_parks1 = Parks.query.filter_by(city=post_city, nation=post_nation).all()
if post_tools:
list_of_parks2 = Parks.query.filter_by(fitness_tools=post_tools).all()
if post_pub:
list_of_parks3 = Parks.query.filter_by(pub_presence=post_pub).all()
if post_games:
list_of_parks4 = Parks.query.filter_by(children_games=post_games).all()
if post_crowded:
list_of_parks5 = Parks.query.filter_by(crowded=post_crowded).all()
if post_fountain:
list_of_parks6 = Parks.query.filter_by(fountain=post_fountain).all()
list_of_parks = Parks.query.filter_by(city=post_city, nation=post_nation).all()
if list_of_parks:
session['parks_list'] = list_of_parks.id_park

Flutter/Dart: How to get list value where key equals

I'm not sure why I'm having such a hard time finding an answer for this, but I have a list that I need to get the value from where the key matches certain criteria. The keys are all unique. In the example below, I want to get the color where the name equals "headache". Result should be "4294930176".
//Example list
String trendName = 'headache';
List trendsList = [{name: fatigue, color: 4284513675}, {name: headache, color: 4294930176}];
//What I'm trying
int trendIndex = trendsList.indexWhere((f) => f.name == trendName);
Color trendColor = Color(int.parse(trendsList[trendIndex].color));
print(trendColor);
Error I get: Class '_InternalLinkedHashMap' has no instance getter 'name'. Any suggestions?
EDIT:
Here's how I'm adding the data to the list, where userDocuments is taken from a Firestore collection:
for (int i = 0; i < userDocument.length; i++) {
var trendColorMap = {
'name': userDocument[i]['name'],
'color': userDocument[i]['color'].toString(),
};
trendsList.add(trendColorMap);
}
I guess, I got what the problem was. You were making a little mistake, and that was, you're trying to call the Map element as an object value.
A HashMap element cannot be called as f.name, it has to be called f['name']. So taking your code as a reference, do this, and you are good to go.
String trendName = 'headache';
List trendsList = [{'name': 'fatigue', 'color': 4284513675}, {'name': headache, 'color': 4294930176}];
//What I'm trying
// You call the name as f['name']
int trendIndex = trendsList.indexWhere((f) => f['name'] == trendName);
print(trendIndex) // Output you will get is 1
Color trendColor = Color(int.parse(trendsList[trendIndex]['color'])); //same with this ['color'] not x.color
print(trendColor);
Check that out, and let me know if that helps you, I am sure it will :)

How to return an JSON object I made in a reduce function

I need your help about CouchDB reduce function.
I have some docs like:
{'about':'1', 'foo':'a1','bar':'qwe'}
{'about':'1', 'foo':'a1','bar':'rty'}
{'about':'1', 'foo':'a2','bar':'uio'}
{'about':'1', 'foo':'a1','bar':'iop'}
{'about':'2', 'foo':'b1','bar':'qsd'}
{'about':'2', 'foo':'b1','bar':'fgh'}
{'about':'3', 'foo':'c1','bar':'wxc'}
{'about':'3', 'foo':'c2','bar':'vbn'}
As you can seen they all have the same key, just the values are differents.
My purpse is to use a Map/Reduce and my return expectation would be:
'rows':[ 'keys':'1','value':{'1':{'foo':'a1', 'at':'rty'},
'2':{'foo':'a2', 'at':'uio'},
'3':{'foo':'a1', 'at':'iop'}}
'keys':'1','value':{'foo':'a1', 'bar','rty'}
...
'keys':'3','value':{'foo':'c2', 'bar',vbn'}
]
Here is the result of my Map function:
'rows':[ 'keys':'1','value':{'foo':'a1', 'bar','qwe'}
'keys':'1','value':{'foo':'a1', 'bar','rty'}
...
'keys':'3','value':{'foo':'c2', 'bar',vbn'}
]
But my Reduce function isn't working:
function(keys,values,rereduce){
var res= {};
var lastCheck = values[0];
for(i=0; i<values.length;++i)
{
value = values[i];
if (lastCheck.foo != value.foo)
{
res.append({'change':[i:lastCheck]});
}
lastCheck = value;
}
return res;
}
Is it possible to have what I expect or I need to use an other way ?
You should not do this in the reduce function. As the couchdb wiki explains:-
If you are building a composite return structure in your reduce, or only transforming the values field, rather than summarizing it, you might be misusing this feature.
There are two approaches that you can take instead
Transform the results at your application layer.
Use the list function.
Lists functions are simple. I will try to explain them here:
Lists like views are saved in design documents under the key lists. Like so:
"lists":{
"formatResults" : "function(head,req) {....}"
}
To call the list function you use a url like this
http://localhost:5984/your-database/_design/your-designdoc/_list/your-list-function/your-view-name
Here is an example of list function
function(head, req) {
var row = getRow();
if (!row){
return 'no ingredients'
}
var jsonOb = {};
while(row=getRow()){
//construct the json object here
}
return {"body":jsonOb,"headers":{"Content-Type" : "application/json"}};
}
The getRow function is of interest to us. It contains the result of the view. So we can query it like
row.key for key
row.value for value
All you have to do now is construct the json like you want and then send it.
By the way you can use log
to debug your functions.
I hope this helps a little.
Apparently now you need to use
provides('json', function() { ... });
As in:
Simplify Couchdb JSON response

How passing string on filter keyword to Django Objects Model?

How can i pass variables on a keyword object filter on a view?
I have:
my_object = MyModel.objects.filter(my_keyword =my_filter_values)
I want to grab my_keyword from a variable coming from a string, like this:
my_string = 'my_keyword'
my_object = MyModel.objects.filter(my_string=my_filter_values)
But this doesn't work because Django doesn't know my_string from MyModel.
Edit: I've found this SO question - I'll test and report back.
You can do something like this:
my_filter = {}
my_filter[my_keyword] = my_filter_value
my_object = MyModel.objects.filter(**my_filter)
As an example, your variables might be:
my_keyword = 'price__gte'
my_filter_value = 10
Which would result in getting all objects with a price >= 10. And if you want to query on more than one field, you can just add another line below my_filter[my_keyword]:
my_filter[my_keyword] = my_filter_value
my_filter[my_other_keyword] = my_other_filter_value

filter using Q object with dynamic from user?

In my views.py I have a method:
#......
def get_filter_result(self, customer_type, tag_selected):
list_customer_filter=[]
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected))
for customer_filter in customers_filter:
customer_filter.list_authorize_sale_type = sale_type_selected(customer_filter.authorize_sale_type)
list_customer_filter.append(customer_filter)
return list_customer_filter
**My case tag_selected is the checkbox values that user checked
I have a problems with tag_selected(is the list=1,2,3,...) that pass from my url
/?customer_type=TDO&tag=2 ===>filter okay
/?customer_type=TDO&tag=3 ===>filter okay
?customer_type=TDO&tag=2,3 ===>How Can I add And condition in filter?
for example
if len(tag_selected)==1:
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected))
else:
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected[0])
Q(tag__id=tag_selected[1])
Q(tag__id=tag_selected[2])
...
)
This works for both single and multiple conditions:
idseq = request.POST['tag'].split(',')
tag_qs = reduce(operator.or_, (Q(tag__id=x) for x in idseq))
Customers.objects.filter(..., tag_qs)