Pyvmomi get folders name - python

I'm new to Python and Django and I need to list all my VMs.
I used pyvmomi and Django but I can't get the folders name from VSphere, it shows a strange line.
VMware list
'vim.Folder:group-v207'
'vim.Folder:group-v3177'
'vim.Folder:group-v188'
I have 3 folders on vSphere so I think my connection it's good but that's absolutely not their names.
Here is my code :
views.py
from __future__ import print_function
from django.shortcuts import render
from pyVim.connect import SmartConnect, Disconnect
import ssl
def home(request):
s = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
s.verify_mode = ssl.CERT_NONE
try:
connect = SmartConnect(...)
except:
connect = SmartConnect(...)
datacenter = connect.content.rootFolder.childEntity[0]
vmsFolders = datacenter.vmFolder.childEntity
Disconnect(connect)
return render(request, 'vmware/home.html', {'vmsFolders':vmsFolders})
home.html
<h1>VMware list</h1>
{% for vmFolder in vmsFolders %}
<div>
<h3>{{ vmFolder }}</h3>
</div>
{% endfor %}
Can anybody help me to get the real names of my folders?

You need to specifically state you want the name, like this:
vmFolders = datacenter.vmFolder.childEntity
for folder in vmFolders:
print(folder.name)

Related

How to route multiple nav items in one folder using flask

I'm developing a tourism website using flask. I have a destinations folder with names of cities. When the dropdown navigation item is clicked, these cities appear and upon click on a city, the page should be redirected to the relevant city. The navigation code is as follows;
<li>Destinations
<ul class="nav-dropdown">
<li>London</li>
<li>Paris</li>
<li>New York</li>
<li>Moscow</li>
<li>Las Vegas</li>
<li>Pataya</li>
</ul>
</li>
The demo.py code is as follows;
from flask import Flask, render_template
#app.route('/destinations/{id}', methods = ['GET'])
def destinations(id):
page = 'destinations/'+id+'.html'
return render_template(page)
How to route this pages properly?
There's only a slight mistake in your code. You have to change the curly braces of id in /destinations/{id} toas /destinations/<id> and then the code will work perfect...
I'd have a context processor, which maintains a dictionary of the required links:
#app.context_processor
def processor():
""" This function injects vars into every page """
cities = {
'paris':'Paris',
'newyork': 'New York',
'moscow':'Moscow',
'vegas':'Las Vegas',
'pataya':'Pataya'
}
return dict(CITIES=cities)
At some point you could build this dictionary from a database or other storage.
Then include in your template:
<li>Destinations
<ul class="nav-dropdown">
{% for city_id,city_name in CITIES.items() %}
<li>{{city_name}}</li>
{% endfor %}
</ul>
</li>
This url_for function, generates a URL like: /destinations/paris.
This method avoids having to manually write city names/ids into your template file.

Context variable to be used in base.html (Django)

I need a certain context variable in my base.html. This is to contain a set of usernames, e.g. [name1, name2, name3, name4,]. If a logged in user's username is part of this list, I give said user certain preferential treatment and show something in the navbar.
To achieve this, I wrote a template tag:
from django import template
from django.db import models
from django.contrib.auth.models import User
register = template.Library()
VIPS = [name1, name2, name3, name4,]
#register.simple_tag
def verified(user):
return VIPS
register.simple_tag(verified)
And then in base.html, I added {% load verified %} at the top, and then:
{% if user.username in verified %}
<!-- do something -->
{% endif %}
This isn't working. What am I doing wrong? I suspect I've written my template tag incorrectly, but I've tried several, more complex approaches (in vain), at least this simpler one made logical sense to me.
My project's a legacy Django 1.5 project with Python 2.7.
You don't need the register.simple_tag(verified) line, as the #register decorator is already doing that.
However, you might consider a different approach to avoid additional processing in the template, assuming your user is coming from request.user...
#regsiter.assignment_tag(takes_context=True)
def check_user_is_verified(context):
user = context['request'].user
return user and user in vips
Then in your template:
{% check_user_is_verified as is_verified %}
{% if is_verified %}
{# whatever #}
{% endif %}
By leveraging an assignment tag, you can check if the user is verified once, and leverage the context variable you assign instead of having to perform the same list processing each time.
Another alternative is to use a cached property on a custom User object, or a "Profile" model that is linked to your User model via a OneToOneField.
from django.utils.functional import cached_property
class Profile(models.Model):
user = models.OneToOneField(User)
#cached_property
def is_verified(self):
# get the list of vips here
return self.user in vips
If your list of vips changes, just clear the cache key, which you could do via a signal or a Celery task, etc:
del profile_instance.is_verified
Now you have a very efficient property you can check anywhere in your code. My preference tends to be fat models, skinny views and dumb templates.

Django dict in template

I'm trying to access some data in a template. I don't think the way I'm doing it now is the best way, but I can't get it even half working any other way.
def room(request, room_id):
#get room data
room = Room.objects.filter(id=room_id).get()
modules = []
#pull all actuator devices for the room
actuators = Device.objects.filter(room_id=room_id,type="actuator")
#build a list of modules then use set to remove duplicates
for actuator in actuators.values():
module = Module.objects.get(module_id=actuator["module_id"]).name_only()
modules.extend([module])
modlist = list(set(modules))
moduleData = {}
#loop through the modules, pull out the required data and send it all off to the template
for module in modlist:
data = Module_List.objects.get(name=module)
dict = {"name": data.name, "widget_mqtt_js": data.widget_mqtt_js, "widget_setup_js": data.widget_setup_js, "widget_body": data.widget_body}
moduleData[module] = dict
print dict["widget_mqtt_js"]
context = {"room_name" : room.name, "actuators" : actuators, "modules" : moduleData}
return render(request, 'control/room.html', context)
This is my code as it stands. The problem I'm having is that the loop in my template is returning blank. It looks like this:
{% for module in modules %}
{{module.widget_mqtt_js}}
{% endfor %}
I think there will be a way to do it with the Module_List model, but I could't get that working either..
modules in the template context is moduleData in your view code. But moduleData is a dict, and iterating over a dict yields its keys, not its values.
You need to iterate over the values, try:
{% for module in modules.values %}
{{module.widget_mqtt_js}}
{% endfor %}

ViewDoesNotExist Error

i am trying to do a simple Django application where employee list is read from database and displayed. for that i defined the models and entered the values to database through Django admin. But while trying to display data from database i am stuck with an error, "ViewDoesNotExist at /employeeProfile/ : Could not import task.employeeDetails.views. Error was: cannot import name emp_profile ".I am relatively new to django,so please help me to solve this. i will paste the code here.enter code here
VIEWS.PY
from django.shortcuts import render_to_response
from django.contrib.auth.models import*
from task.employeeDetails.models import *
from django.conf import settings
from django.http import HttpResponse
from task.employeeDetails import emp_profile
def employeeList(request):
tableList = EmployeeDetails.objects.all()
return render_to_response('employeeList.html', {'emp_list': tableList})
def employeeProfile(request):
profile = EmployeeDetails.objects.all()
return render_to_response('employeeProfile.html',{'emp_profile':emp_profile})
URLS.PY
(r'^employeeProfile/$','task.employeeDetails.views.employeeProfile'),
TEMPLATE
<html>
<body>
{%for emp in emp_profile%}
<tr> <td>{{ emp.userName }} {{ emp.designation }} {{ emp.employeeID }}</td> </tr><td>
{%endfor%}
</table></h4>
</body>
</html>
def employeeProfile(request):
profile = EmployeeDetails.objects.all()
return render_to_response('employeeProfile.html',{'emp_profile':emp_profile})
You named it profile on line 2, and then you tried to put it in the dictionary as emp_profile on line 3.
from task.employeeDetails import emp_profile
What is emp_profile and where exactly is it? from the looks of it, employeeDetails is the name of your directory, so unless emp_profile is a file in employeeDetails/, is defined in employeeDetails/__init__.py (or otherwise imported there), it will throw an import error.
I assume you want:
def employeeProfile(request): profile = EmployeeDetails.objects.all()
return render_to_response('employeeProfile.html',{'emp_profile':profile})
As Yuji pointed out, it looks like emp_profile isn't defined anywhere

How to display total record count against models in django admin

Is there a neat way to make the record/object count for a model appear on the main model list in the django admin module?
I have found techniques for showing counts of related objects within sets in the list_display page (and I can see the total in the pagination section at the bottom of the same), but haven't come across a neat way to show the record count at the model list level.
I would look into the models.Manager class. A subclass of Manager will allow you to add table-level functionality to your models. A Manager method can return any data you want and there is an interesting example in the Django DB API documentation. You may then be able to pull this into Admin by adding a admin inner class to your model.
from django import template
from django.db.models.loading import get_model
register = template.Library()
#register.simple_tag()
def get_model_count(admin_url):
app_label, model_name = admin_url.split('/')[:2]
return get_model(app_label, model_name, seed_cache=False).objects.count()
Then copy and override "/templates/admin/index.html" from "django's contrib/admin/templates/index.html".
At the top add:
{% load NAME_OF_YOUR_TAG_FILE %}
Add the following call after the model name or wherever:
{% get_model_count model.admin_url %}
This fits nicely into this use case. You're done!
I didn't find any nice way to add count of models in the main admin page, but here is the solution that I finally use.
In short I compute the counts of each models in signals post_delete and post_save methods, store the variables in the custom request (in a map) and display it in the extended admin index.html by simply checking with an if for each desired models.
The extended templates/admin/index.html:
{% if model.perms.change %}
<th scope="row"><a href="{{ model.admin_url }}">{{ model.name }}
{% if model.name == "Mymodel1_verbose_name_plural" %} ({{ MODELS_COUNT.Mymodel1}}) {% endif %}
</a></th>
{% else %}
My custom request in util/context_processors.py:
from myproject import settings
def myproject(request):
return {
'request' : request,
'MODELS_COUNT' : settings.MODELS_COUNT
}
In my settings.py:
MODELS_COUNT = {
'Mymodel1': None,
'Mymodel2': None
}
TEMPLATE_CONTEXT_PROCESSORS = (
...
'myproject.util.context_processors.myproject',
)
In myproject.__init__.py:
from django.db.models.signals import post_save, post_delete
def save_mymodel1_count(sender, instance=None, **kwargs):
if kwargs['created']:
settings.MODELS_COUNT['Mymodel1'] = Mymodel1.objects.count()
def delete_mymodel1_count(sender, instance=None, **kwargs):
settings.MODELS_COUNT['Mymodel1'] = Mymodel1.objects.count()
settings.MODELS_COUNT['Mymodel1'] = Mymodel1.objects.count()
post_save.connect(save_mymodel1_count, sender=Mymodel1)
post_delete.connect(delete_mymodel1_count, sender=Mymodel1)
If you have lots of models, I suggest that you transform this in a more generic solution.

Categories

Resources