Get list of templates with pyvmomi Vmware vCenter - python

I would like to list all template available un my vCenter.
I dont know how do this. I try to get all object in content.rootFolder and compare if it's a virtualmachine or not. But I can't find templates.
I see i can do this:
container = content.viewManager.CreateContainerView(
content.rootFolder, [[vim.VirtualMachine]], True)
but nothing,
thanks for ur help. With that, I suppose I am able to find a specific template.

You are looking for vm.config.template if that property is true the VirtualMachine is marked as a template. You should be using a property collector to make your code fast. Take a look at this sample. There is a list of vm_properties starting on line 38. You could remove them and just use "name" and "config.template" if those are the only things you care about. Then modify the printing at the bottom.. add a simple if vm["config.template"]: xxx so it only printed if that property was set.. something like that.

Related

Add attribute to object

I have an var containing all documents from mongoDB as an object. The way I set this is like this:
questions = Questions.objects.order_by('-openDate')
This works fine. When called, the objects show the attributes I expect. But now I want to add an attribute to it. Its not defined in the database, but I will set it base on some simple python code. To break it down:
One of the fields is responses, which contain an userId and response.
By going through all responses:
for i in question.responses:
if i.id == current_user:
(Now the magic should happen)
Now comes what does not work. I want to add an attribute userResponded to the object. This way in the template I can simply ask if userResponded is true or false. To be clear, the userResponded should not be added to responses, but a new attribute.
Just to add to this, I already tried:
questions[0].test = 'test'
I expected it was now added to the first object in questions. However, this did not happen.
Please help, already stuck on this for way too long!

SQLAlchemy Query - Dynamic class selection

I can find many examples of how to build these queries where the 'filter_by' part is dynamic, but I cant seem to find anything where the class name is the dynamic bit. I'm sure an answer must be out there, just not sure what to search for.
My use case it this: I need to build a dynamic SQLAlchemy query. The twist is that its the class name changing rather than the filter variables. The query type will always be a '.get()' so I'm good there. I should also say that simply plugging a variable in where the class name should be doesnt work.
db_model = request.values.get("db_model_class")
item_id = request.values.get("item_id")
result = db.session.query(db_model).get(int(item_id))
How do I go about making this work?
Create a lookup of relevant classes:
models = {"Foo": Foo,
"Bar": Bar,
"...": ...}
and get the class:
db_model = models[request.values.get("db_model_class")]
db_model = request.values.get("db_model_class")
item_id = request.values.get("item_id")
Maybe the problem is here.
you need to set a debug point.
the answer by Ilja Everilä was great. so you need to check the way you get the parameters.
if you are using a pycharm, configure a debug setting.
if you are using Macbook,
click the run->edit configurations->
then you click the left margin of the code, and restart your app with the debug button on the top right corner. when you request the url again, you will see what your view function has get in the request object.

Odoo - Changing user group id just right after signup (ecommerce)

I'm using Odoo 10. After a new user sign up (through localhost:8069/web/signup) i want him to be automatically allocated inside a group i created on my very own custom module (the user will need authentication from an admin later on so he can be converted to a regular portal user; after signup he will receive restricted access).
I have tried many things. My latest effort looks like this:
class RestrictAccessOnSignup(auth_signup_controller.AuthSignupHome):
def do_signup(self, *args):
super(RestrictAccessOnSignup, self).do_signup(*args)
request.env['res.groups'].sudo().write({'groups_id': 'group_unuser'})
Note that I have import odoo.addons.auth_signup.controllers.main as auth_signup_controller so that I can override the auth_signup controller.
I have located that method as the responsible for doing the signup. So I call it in my new method and then try to change the newly created user's group_id.
What i miss is a fundamental understanding of how to overwrite a field's value from another model inside a controller method context. I'm using the 'request' object although i'm not sure of it. I have seen people using 'self.pool['res.users'] (e.g.) for such purposes but i don't understand how to apply it inside my problem's context.
I believe, also, that there is a way to change the default group for a user after it is created (i would like to know), but i also want to understand how to solve the general problem (accessing and overwriting a field's value from another module).
Another weird thing is that the field groups_id does exist in 'res.users' model, but it does not appear as a column in my pgAdmin interface when i click to see the 'res.users' table... Any idea why?
Thanks a lot!
i don't know if after calling :
super(RestrictAccessOnSignup,self).do_signup(*args)
you will have access to user record in request object but if so just add
the group to user like this, if not you have to find where the user record or id is saved after calling do_signup because you need to update that record to ad this group.
# create env variable i hate typing even i'm typing here ^^
env = request.env
env.user.sudo().write({'groups_id': [
# in odoo relation field accept a list of commands
# command 4 means add the id in the second position must be an integer
# ref return an object so we return the id
( 4, env.ref('your_module_name.group_unuser').id),
]
})
and if changes are not committed in database you may need to commit them
request.env.cr.commit()
Note: self.env.ref you must pass the full xmlID.
This is what worked for me:
def do_signup(self, *args):
super(RestrictAccessOnSignup, self).do_signup(*args)
group_id = request.env['ir.model.data'].get_object('academy2', 'group_unuser')
group_id.sudo().write({'users': [(4, request.env.uid)]})
In the get_object i pass as arguments the 'module' and the 'xmlID' of the group i want to fetch.
It is still not clear to me why 'ir.model.data' is the environment used, but this works as a charm. Please note that here we are adding a user to the group, and not a group to the user, and to me that actually makes more sense.
Any further elucidation or parallel solutions are welcome, the methods aren't as clear to me as they should be.
thanks.

Model relationship to html template

I've been struggling for this issue for a few hours - I know there's probably a simple solution that I'm overlooking.
I have a one to many relationship with my models.
I have need to return all rows of one object with the rows for the related object.
In a sense I have this:
object
object
object_relationship.property
object_relationship.property
object
object_relationship.property
object
Now - I can run through all of these fine, but I run into an issue when I want to send these back to the html template.
I can send the object back - but how do I send the object_relationship back in the order that I have it above?
Does this make sense?
You might not need to worry too much about this, acutally... look at these models:
class Venue(base.NamedEntity, HasPerformances, HasUrl, HasLocation):
city = db.ReferenceProperty(City, collection_name='venues')
url = db.StringProperty(required=True, validator=validators.validate_url)
location = db.GeoPtProperty()
class Performance(base.Entity):
show = db.ReferenceProperty(Show, collection_name='performances', required=True)
utc_date_time = db.DateTimeProperty(required=True)
venue = db.ReferenceProperty(Venue, collection_name='performances', required=True)
In a case like this, nothing stops you from using venue.performances from either code or templates and treating it as a list. The API will automatically fire queries as needed to fetch the actual objects. The same thing goes for performance.venue.
The only problem here is performance - you've got a variant of the n+1 problem to deal with. There are workarounds, though, like this article by Nick Johnson. I'd suggest reading the API code too... it makes for interesting reading how the property get is captured and dereferenced.
My first suggestion is to denormalize the data if you are going to do many reports like that. For example, maybe you could include object.name on the object_relationship entity.
That said, you could send a list of dicts to your template, so maybe something like:
data = []
for entity in your_query:
children = [{'name': child.name} for child in entity.object_relation]
data.append({'name': object.name,
'children': children,
...
})
Then pass the data list to your template, and process it.
Please note, this will perform very badly. It will execute another query for every one of the items in your first query. Use Appstats to profile your app.

Exception when using filter to retrieve a django model

To retrieve a django object, I am using the filter function as follows:
product = Product.objects.filter(code=request.POST['code'])
Then, when I try to access the retrieved object as:
product[0].description
I get an exception "list index out of range". Although, the filter is indeed returning an object because the len(product) call is showing "1".
However, if I hardcode the code value (retreived from the post above), I get no exception.
All I want to do is get access to the product object based on the code.
Using Product.objects.get does not work either...
Any help will be appreciated.
Thanks in advance.
You should probably validate that request.POST['code'] is valid before you try to use it in anything:
# code will be None if it isn't found in request.POST
code = request.POST.get('code')
if code:
products = Product.objects.filter(code=code)
for product in products:
print product.description
Hope this helps a bit.
It's not an answer but in this type of case, where the results make no sense, it's normally time to get the debugger out (either pdb or preferably ipdb).
import ipdb;ipdb.set_trace()
Then look at product. What actually is it? Look at request.POST['code'] and see what is different from just passing a literal. Also would be interested to know what the attempt to use 'get' actually does. You say it doesn't work but what does it actually do?

Categories