i have tried 100 times i do not know what is wrong with this code. somebody please help me to sort out this issue or tell me what i am doing wrong to below code.
Every time i receive:
builtins.TypeError TypeError: getCategoryItems() missing 1 required
positional argument: 'cat_id'
Code:
#app.route('/')
def getAllItems():
return redirect(url_for('getCategoryItems', category_name='ab', cat_id=1))
#app.route('/<string:category_name>/items/')
def getCategoryItems(category_name, cat_id):
id = cat_id;
items = session.query(Item).filter_by(category_id=id).all()
output = ''
for item in items:
output += item.title + '</br>'
return output
You don't need to pass category_name, you only need the category id. The category name should be contained in each of the item fetched from the database.
You're getting an error because cat_id is not defined when the function def getCategoryItems(category_name, cat_id) is called.
I would suggest, however, if you want to really get all items to just use:
#app.route('/')
def getAllItems():
items = session.query(Item).all()
...
For more info, have a look at the flask-sqlalchemy docs.
Related
Hello i would like to increment the field current_week of all objects in the collection tournaments but i get an error. I have the code:
class DataBase:
def __init__(self):
self.myclient = pymongo.MongoClient("mongodb://localhost:27017/")
self.mydb = self.myclient["MMA_TOURNAMENT"]
self.tournaments = self.mydb["tournaments"]
def insert_new_tournament(self, tournament):
print(tournament.__dict__)
self.tournaments.insert_one(tournament.__dict__)
def increment_day(self):
self.tournaments.update({'$inc': {'current_week' : 1}})
and i get the error:
TypeError: update() missing 1 required positional argument: 'document'
when calling the function. I am a beginner in pymongo I really don't know what query I should put there. Thank you!
You need to pass a filter as the first parameter to update_many(); to update every document your filter is simply {}.
def increment_day(self):
self.tournaments.update_many({}, {'$inc': {'current_week' : 1}})
I'm working on suppliers form view (res.partner model).
i've tried to have the current record's id by the code below:
current_id=fields.Integer(compute='get_current_id')
#api.multi
def get_current_id(self):
print self.id
self.current_id=self.id
with this code, i have the error : "ValueError: Expected singleton: res.partner(1, 50)" which is weird because 50 is my current record id but i don't know why it's getting the id 1 also. When i've looked for it in pgAdmin, i found out that 1 is the "company_id". Why the current record (view form) is having two ids?
Thanks.
You are using #api.multi, so self can be more than one record.
You can try:
#api.multi
def get_current_id(self):
for instance in self:
instance.current_id = instance.id
Or:
#api.one
def get_current_id(self):
self.current_id = self.id
I see this question has been asked before in different variations, but I feel as though I have implemented the feedback I have seen in those threads (mainly making sure the object is created as I have done in the second last night, and making sure the dictionary is initiated, which I feel I have done in the third line) and I am still receiving the error. Any advice would be very much appreciated. Thank you!
class Groceries:
def __init__(self, grocery_list):
self.grocery_list = {}
def add_item(self, item):
item = input("name: ")
purchased = input(False)
self.grocery_list[item] = purchased
something = Groceries()
something.add_item()
The error I get is:
Traceback (most recent call last):
File "intermediate_python.py", line 14, in <module>
something = Groceries()
TypeError: __init__() missing 1 required positional argument: 'grocery_list'
I tried to resolve this error by removing grocery_list from the def init statement (not sure why this would work, I was just playing around) and the error was moved to the next line with:
Traceback (most recent call last):
File "intermediate_python.py", line 15, in <module>
something.add_item()
TypeError: add_item() missing 1 required positional argument: 'item'
To initialise an instance of your Groceries class you need to provide the parameter "grocery_list" which is defined in your init method
class Groceries:
def __init__(self, grocery_list):
self.grocery_list = {}
Try create your instance using the following:
something = Groceries({"milk": 1, "butter": 1})
Alternatively, to allow for empty Groceries objects, you can add a default parameter to the init method, you should also be assigning the value of the parameter to the variable self.grocery_list instead of assigning it an empty dictionary:
class Groceries:
def __init__(self, grocery_list={}):
self.grocery_list = grocery_list
and also with your method add_item, again you need to pass a parameter or else removed the parameter (since you're asking for it as input)
def add_item(self):
item = input("name: ")
purchased = input("amount: ")
self.grocery_list[item] = purchased
something = Groceries({"milk": 0})
something.add_item()
>> name:
>>> milk
>> amount:
>>> 1
def __init__(self, grocery_list):
self.grocery_list = {}
Although you are passing a grocery_list to your constructor, you are not actually using it to set the value. You merely need to set self.grocery_list equal to the passed argument grocery_list to fix this as I do below.
def add_item(self, item):
item = input("name: ")
You are also trying to both pass item as an argument and input it manually in the function. This means that regardless of what input you send to add_item, you will always override that value with user input. You can fix this by making the item argument optional and checking if it was passed before prompting the user for input as I do below.
purchased = input(False)
self.grocery_list[item] = purchased
Also, it is unclear here why you are fetching input with an implicit conversion of the boolean value False to string as a second prompt after asking for the item name. It seems that you want to set some purchased value to True or False, but it is also unclear then why you are using a dictionary for making a list of groceries in the first place unless you intend to include the quantity as the dictionary value. If you just wanted to see if an item was on the grocery list you could use the set() type instead of dict(). This might serve as an example to help you move forward if you want to maintain quantities.
class Groceries:
def __init__(self, grocery_list={}):
self.grocery_list = grocery_list
def add_item(self, item='', qty=1):
if not item: item = input('name: ')
if item in self.grocery_list:
self.grocery_list[item] += qty
else:
self.grocery_list[item] = qty
def item_qty(self, item=''):
if not item: item = input('name: ')
return(self.grocery_list[item])
def print_all(self):
for key, val in self.grocery_list.items():
print(val, key)
something = Groceries()
something.add_item('apple') # add one apple to groceries
print(something.item_qty('apple'))
something.add_item('apple', 3) # add three apples to groceries
print(something.item_qty('apple'))
something.add_item() # add arbitrary item to groceries
something.print_all() # print all groceries
If you are creating an instance of the Groceries class (something = Groceries(*args)), at the end of the initialization, the Groceries.__init__() function gets called with the same argument list *args.
That means, when you write something = Groceries(), you are trying to call the __init__ function without arguments. On the other hand, the function has a required positional argument grocery_list (any positional argument is required if you didn't provide a default for it).
Since your code defines the grocery_list as an empty dictionary anyway, you don't need to have this an argument to your __init__ function, you can simply use:
def __init__(self):
self.grocery_list = {}
Which will fix the error.
Or you can have a default value and use:
def __init__(self, grocery_list={}):
self.grocery_list = grocery_list
Which would let you use __init__ without providing the grocery_list argument, and using {} in that case.
The exact same case holds for the add_item function: you are defining it with a required positional argument, and then you are trying to call it without any argument. Since you aren't passing any value to the function on the function call that you would later use, you can again remove the argument and simply use:
def add_item(self):
I want to pass a jlist (which I generate everytime the 'javaindex' method is called) to another view i.e the javaresult view. I am generating the jlist from the Question model.
def javaindex(request):
javapool = list(Question.objects.all())
random.shuffle(javapool)
jlist = javapool[:10]
request.session['jlist'] = jlist
return render(request,'index.html',{'latest_question_list': jlist})
My other view is
def javaresult(request):
ch = [0]
correct = 0
jlist = request.session['jlist']
for i in range(1,11):
s = request.POST.get(str(i))
if s:
question, choice = s.split('-')
ch.append(choice)
if jlist[i].ans == ch[i]:
correct+=1
return HttpResponse(correct)
I searched on SO and hence added the request.session['jlist'] but that is giving me an error <Question: Question object> is not JSON serializable.
How do i get rid of this? Thanks :)
Save ids of the Question objects in the session and get objects from DB in second view again.
def javaindex(request):
...
request.session['jlist'] = [j.id for j in jlist]
...
def javaresult(request):
...
jlist = Question.objects.filter(id__in=request.session['jlist'])
...
Here is Customer class:
class Customer:
def __init__(self, timestamp, cid, item_count):
self.time_stamp = timestamp
self.customer_name = cid
self.item_count = item_count
def checkout(self, new_timestamp):
self.time_stamp = new_timestamp
def get_cus_name(self):
return self.customer_name
If I create an empty list of Customer objects like:
customers = [Customer]
And then somewhere else I try to call Customer methods in a loop like:
def checkout_customer(self, cid):
for cus in self.customers:
if cus.get_cus_name == cid:
cus.checkout(self.cur_num_customers + 7)
why do I get an error when I try to call cus.checkout? My ide tells me that it expects a Customer but got an int. Why doesn't it pass itself into the 'self' arg here?
However if I just create a Customer object and directly call its methods, it works fine:
def foo(self):
cus = Customer(1,'pop',2)
cus.checkout(23)
This is my first time learning python, and ive been stuck trying to figure out lists, and accessing its members. Perhaps my initialization of self.custormers = [Customer] is incorrect?
EDIT:
In my constructor of tester class I create an empty list like this:
self.customer = [Customer]
I am able to add customers no problem:
def add_custormer(self, customer):
self.customers.append(customer)
My problem is not adding customers, but accessing their methods once they are in a list. Doing something like this self.customers[0].checkout(1,'pop',2) gives me an error "Expected type 'Customer' got int".
I am not sure of the class where checkout_customer lives but I am assuming you declare the list self.customers somewhere in it.
self.costumers = []
If you intend to add an element Customer to the list you should use something like: self.customers.append(Customer(x,y,z)) since you want to add a new customer to the list and when doing so you are required to initialize the Customer class.
I didn't try the code but I believe something like this should work:
def foo(self):
self.customers.append(Customer(1,'pop',2))
self.checkout_customers(23)