ViewDoesNotExist Error - python

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

Related

Django Queryset is not iterable

Right now i am trying to pull all of the objects out of my database and display them onto a web page using django and PostgreSQL, the syntax is slightly different due to the use of the Django Mako Plus framework, but the underlying code is the same. The only major difference is that in the template the syntax is changed from {{code here}} to ${code here}.
Here is my view:
from django.conf import settings
from django_mako_plus import view_function
from datetime import datetime
from django.http import HttpResponse, HttpResponseRedirect
from django import forms
from homepage import models as cmod
from django.contrib.auth import authenticate, login
from django.shortcuts import render
from homepage.models import User
# from homepage.models import
from homepage.models import DReferForm
import random, string
#view_function
def process_request(request):
dReferral = DReferForm.objects.all()
context = {
'dReferral':dReferral,
}
# The DMP Equivalent when rendering the page
return request.dmp.render('submissions.html', context)
Here is my template:
<%inherit file="base.htm" />
<%block name="content">
<h1>Testing</h1>
%for i in dRefferal:
<p>Doctor Name: ${i.Fname}</p>
%endfor
</%block>
Whenever I try to load the webpage, I get an object not iterable error.
If I use this exact same code on any other model it works just fine and pulls all the data.
Thank you for all your help.
You have a typo in the template - dRefferal for dReferral.

API Integration in Django

I am trying to use the OpenDOTA API in my pet project. At the moment, I am having problem displaying the content of the API into my CBV.
My views.py:
from django.views.generic import TemplateView
import requests
import json
# Create your views here.
class HeroList(TemplateView):
template_name = 'dota/heroes.html'
url = 'https://api.opendota.com/api/heroes'
r = requests.get(url)
r.text
result = r.json()
I am lost on how to call the json in my HTML. I've tried running the same code in python IDLE, and when I type the "result" and hit enter, it gives my the dict. Any idea on how should I display the dict into my template?
What you need to do is first dump your json to a dictionary format.
import json
from django.shortcuts import render
rdict = json.loads(r.json())
return render(request, template_name=<template name>, context=rdict)
All this reside insides your function inside your views.py
Now after this using Django template language - https://docs.djangoproject.com/en/1.11/topics/templates/
You can render data in keys in your dictionary to your template.
If you mean accessing the result in html, then below is a sample.
choices = {'key1':'val1', 'key2':'val2'}
Here's the template:
<ul>
{% for key, value in choices.items %}
<li>{{key}} - {{value}}</li>
{% endfor %}
</ul>
from this answer how to access dictionary element in django template?

Pyvmomi get folders name

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)

How to insert data to django database from views.py file?

How can I insert data to my django database from a function in the views,py file? Is python manage.py shell the only way to insert?
For more explanations I'm using:
python 3.4
django 1.8.2
PyMySQL
For example:
models.py:
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=30)
city = models.CharField(max_length=60)
views.py:
from django.http import HttpResponse
import pymysql
from books.models import Publisher
def send(request):
p = Publisher(name='Apress', city='Berkeley')
p.save()
urls.py
from niloofar.views import send
url(r'^index/', send),
I want when the page index is loaded, the send function works and insert data to database.
It does not work. It does not give any error and also nothing happened when i refreshed the index page, nothing was sent to database. I think there is mistake in syntax, in the way i'm trying to insert data.
Let me notice that even when I run python manage.py shell then:
from books.models import Publisher
p = Publisher(name='Apress', city='Berkeley')
p.save()
nothing will be inserted to django database.
Your question is very unclear. You should probably go through the django-tutorial.
But sure you can insert data into the db from views. Assume you have a model called Foo:
models.py
class Foo(models.Model):
name = models.CharField(max_length=100)
view.py
from .models import Foo
def some_name(request):
foo_instance = Foo.objects.create(name='test')
return render(request, 'some_name.html.html')
You can just create an instance of one of your models and save it. Suppose you have an Article model:
from django.http import HttpResponse
from django.template import loader
from .models import Article
def index(request):
article = Article()
article.title = 'This is the title'
article.contents = 'This is the content'
article.save()
template = loader.get_template('articles/index.html')
context = {
'new_article_id': article.pk,
}
return HttpResponse(template.render(context, request))
An easy way to do this would be to make use of create function. By mentioning the field name and their values. The following illustrated code helps you to insert data into your database from views.py and display the contents of database into the html page.
Suppose we have a table which looks something like this
Name Age Marks
Bunny 4 10
Tanishq 12 12
The models.py looks something like this
from django.db import models
# Create your models here.
class Student(models.Model):
student_name = models.CharField(max_length = 120)
student_age = models.IntegerField()
student_marks = models.IntegerField()
So the views.py would look something like
from django.shortcuts import render
from .models import Student # Student is the model class defined in models.py
# Assuming the data to be entered is presnet in these lists
stud_name = ['Aman', 'Vijay']
stud_age = [13, 12]
stud_marks = [20, 22]
def my_view(request, *args, **kwargs):
# Iterate through all the data items
for i in range(len(stud_name)):
# Insert in the database
Student.objects.create(Name = stud_name[i], Age = stud_age[i], Marks = stud_marks[i])
# Getting all the stuff from database
query_results = Student.objects.all();
# Creating a dictionary to pass as an argument
context = { 'query_results' : query_results }
# Returning the rendered html
return render(request, "home.html", context)
The following should be the home.html file to display all entered data
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>HOME</h1>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Marks</th>
</tr>
{% for item in query_results %}
<tr>
<td>{{ item.student_name }}</td>
<td>{{ item.student_age }}</td>
<td>{{ item.student_marks }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
Below change required for the insert, otherwise you will get type error
Student.objects.create(stud_name = stud_name[i], stud_age = stud_age[i], stud_marks = stud_marks[i])
you may try this:
def myFunction(request):
myObj = MyObjectType()
myObj.customParameter = parameterX
...
myObj.save()

How do I get POST data from a free text field?

Doing a modified version of the polls tutorial. Comments work with the database when I go in the python manage.py shell but I can't get it to actually read the post data. Any time I post a comment, the page re-renders but no comment in the database.
Here are my models for an individual Entry and a Comment
import datetime
from django.db import models
from django.utils import timezone
from django.forms import ModelForm
class Entry(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
class Comment(models.Model):
entry = models.ForeignKey(Entry)
comment = models.TextField()
comment_date = models.DateTimeField()
In the Python shell, I'm able to create comments (that show up in the admin) perfectly.
>>> from blog.models import Entry, Comment
>>> e = Entry.objects.get(pk=1)
>>> from django.utils import timezone
>>> e.comment_set.create(comment="isn't it pretty to think so?", comment_date=timezone.now())
<Comment: isn't it pretty to think so?>
In the detail.html view of each blog entry, a user can add a comment.
<h1>{{ entry.title }}</h1>
<p>{{ entry.body }}</p>
<p>{{ entry.tags_set.all }}</p>
<form action="{% url 'blog:comment' entry.id %}" method="post">
{% csrf_token %}
<textarea name="comment101" style="width:300px; height: 70px; maxlength="300"; display:none;">
</textarea></br>
<input type="submit" name="comment101" value="Add comment" />
</form>
Views for detail and comment:
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from blog.models import Entry, Tags, Comment
def detail(request, entry_id):
entry = get_object_or_404(Entry, pk=entry_id)
return render(request, 'entries/detail.html', {'entry': entry})
def comment(request, entry_id):
p = get_object_or_404(Entry, pk=entry_id)
add_comment = request.POST['comment101']
#get input name comment from POST data
p.comment_set.create(comment="add_comment", comment_date=timezone.now())
return HttpResponseRedirect(reverse('blog:detail', args=(p.id)))
I've exhausted all I know. I tried adding name='comment101' every input/form in detail.html and my comment view replicates exactly what I did in the Python shell.
Lastly, if anyone could point me to something to debug code involving POST data (for Mac), that'd be helpful. Thank you.
I recommend you to use request.POST.get to get post data:
add_comment = request.POST.get('comment101',None)
Where None is the default value if nothing is passed. Then in the following lines you should check whether add_comment is None or not by a simple if statement:
if add_comment is not None:
#do the work
I also recommend you to control the request type with request.method == 'POST'.
Then you can create the comment:
comment = Comment()
comment.comment = add_comment;
comment.comment_date = timezone.now()
comment.entry = p
comment.save()
To debug, I personally use print keyword. If you would like to see all post data you can iterate and print them. When you use print keyword or method (for python 3) you can see the output in from ./manage.py runserver outputs.
for key, value in request.POST.iteritems():
print key, value
I would use
c = Comment(comment=add_comment, comment_date=timezone.now(), entry=p)
c.save()
That might be of some use.
Also if you want to debug code it is best to place
import pdb; pdb.set_trace()
which gives you interactive console wherever you want it.
In case you want to use something better use ipdb (pip install ipdb)
import ipdb; ipdb.set_trace()

Categories

Resources