Django Unable to show content from DB - python

I'm new with Django and i'm trying to show some data from my db but with no luck.
The DB connection is OK and i did syncdb.
I'm trying to iterate on one column of my database (logging) table (handleName)
Model:
class Handle(models.Model):
handleName = models.CharField(db_column='handleName', max_length=200)
def __unicode__(self): # Python 3: def __str__(self):
return self.handleName
View:
def logger(request):
#query_results = Handle.objects.all()
#return render(request, 'ate_logger/logger.html')
query_results = Handle.objects.all()
t = loader.get_template('ate_logger/logger.html')
c = Context({
'query_results': query_results,
})
return HttpResponse(t.render(c))
Html template:
{% if query_results %}
<ul>
{% for handle in query_results %}
<li> name {{ handle.handleName }} </li>
{% endfor %}
</ul>
{% else %}
<p>No data available</p>
{% endif %}
The problem is that i'm getting No data available but i know for sure i have the data in the db. I've tried to use the tutorial but every thing i do seems OK so maybe someone can suggest a solution?
EDIT-1
I'll try to add some mote information i have a data base with data made by another software, i want to connect with Django to that database and show it's content.
as first step i'm trying to iterate on table Handle column idHandle and to show all the values.
the problem is that i have no return values in return self.handleName
I have tried it also in the manage.py shell and it's also empty.

Problem is solved by #yuvi help!
Auto modeling the db was the needed option.
docs.djangoproject.com/en/dev/howto/legacy-databases

Related

How to show data from django models whose boolean field is true?

verified = models.BooleanField(default=False)
I want to show only that objects in frontend whose verified field is true in Django models.
There are many ways
you can handle this on your views
in views.py
modelList = modelname.objects.filter(verified=True)
also you can handle it on HTML
in views.py
modelList = modelname.objects.all()
in html
{% for models in modelList %}
{% if models.verified == True %}
# Your Code
{% endif %}
{% endfor %}
You filter the items with:
MyModel.objects.filter(verified=True)
with MyModel the model that contains the verified field.
you have to ways to achive that that either it with your views or html
first views
you can filter your model to return only object which is verfied like this
name = modelname.objects.filter(verified=True)
second way
or you can pass in html while you are requesting all object of that field in views
in views
name = modelname.objects.all()
then in html while fetching data
{% for name in models %}
{% if name.verified == True %}
then pass the object which are verified
{% else %}
pass another data
{% endif %}
{% endfor %}
i hope now you got my point tell me if you got any error while implementing any of these code

Returning a list using flask and SQLite

I was wondering how I could return individual values from an SQLite table into a list using flask. At the moment the result is showing all three available values from the table but I want them to be listed individually (green text). Below I print the values in the code to show you what I would like reflected on the webpage. The end goal is for each to be a link to the respective ad. Frankly I am pretty new and am stuck so any direction would be super helpful on what the next steps should be here. The links to the respective ads will be done with dynamic URLs which I believe I know how to do. Right now, I just want to know if I could get the values from the flask template.
app.py
#app.route("/my_ads")
#login_required
def my_ads():
conn = sqlite3.connect('food.db')
conn.row_factory = lambda cursor, row: row[0]
c = conn.cursor()
ads = c.execute("SELECT image_key FROM food").fetchall()
for row in ads:
print(row)
return render_template("my_ads.html", ads=ads
my_ads.html
{% extends "layout.html" %}
{% block main %}
...
<div class="row">
<div class="column">
<h2>My Ads</h2>
<ul>
{% for ad in ads %}
<li>{{ads}}</li>
{% endfor %}
</ul>
</div>
{% endblock %}
In your <ul>'s for loop, instead of using <li>{{ads}}</li>, use just <li>{{ad}}</li> to access the individual values.

In Django, how do I query a MYSQL database for the logged in user? (i.e results for specific user without hardcoding the user id)

I have this so far, apologies I am new to programming - trying to learn Django and Python.
View:
def dashboard(request):
return render(request, 'app/dashboard.html', {'my_custom_sql': my_custom_sql})
below function does't output anything in the template
def my_custom_sql(self):
return self.request.CustomUser.customuser_set.all()
alternative to above using hardcoded raw SQL:
def my_custom_sql():
current_user = 1
with connection.cursor() as cursor:
cursor.execute("SELECT first_name FROM customuser WHERE id =
%s",[current_user])
row = cursor.fetchone()
above works, but I can't find a way of passing the userid to the query without hardcoding it into the user variable.
Template:
<h3> Displaying User's First Name </h3>
{% if user.is_authenticated %}
<p>The first name: {{my_custom_sql}}</p>
{% endfor %}
andtmc. Welcome to SO.
You do need to close if tag:
template
{% if user.is_authenticated %}
<p>The first name: {{my_custom_sql.first_name}}</p>
{% endif %}
views.py
def dashboard(request):
return render(request, 'app/dashboard.html', {'my_custom_sql': my_custom_sql(request)})
def my_custom_sql(request):
return CustomUser.objects.get(pk=request.user.pk)
Depending on your model, you can just:
{% if user.is_authenticated %}
<p>The first name: {{user.first_name}}</p>
{% endif %}

Django: Listing documents from a local folder

I've been trying to find a way to display my documents from a local folder on to a web page. I was wondering about this in two ways: one was to use django's ListView, but I am not using models in this case, so I am unsure if it would work. The other way I'm going with this is by through this list method that I've made, but I am having trouble getting the proper contents (title, date) on to the webpage. They show up in lists that I created, but wont translate to the webpage. Its just a blank page. Here's my code:
views.py
import os, string, markdown, datetime
from P1config.settings import STATICBLOG_COMPILE_DIRECTORY,STATICBLOG_POST_DIRECTORY,STATICBLOG_STORAGE
def doclist(request):
mdown = markdown.Markdown(extensions = ['meta','extra', 'codehilite', PyEmbedMarkdown()])
posts = []
for item in os.listdir(STATICBLOG_POST_DIRECTORY):
if item.endswith('.md'):
continue
try:
with open(os.path.join(STATICBLOG_POST_DIRECTORY, item)) as fhandle:
content = fhandle.read() # (opening and reading the ENTIRE '.md' document)
mdown.convert(content) # (converting file from '.md' to ".html")
post = { 'file_name' : item }
if 'title' in mdown.Meta and len(mdown.Meta['title'][0]) > 0:
post['title'] = mdown.Meta['title'][0]
else:
post['title'] = string.capwords(item.replace('-', ' '))
if 'date' in mdown.Meta:
post['date'] = mdown.Meta['date'][0]
post['date']= datetime.datetime.strptime(post['date'], "%Y-%m-%d")
posts.append(post)
except:
pass
from operator import itemgetter
posts = sorted(posts, key=itemgetter('date'))
posts.reverse()
return render(
request,
'list.html',
{'post' : posts}
)
list.html
{% extends 'base.html' %}
{% block content %}
{% if post %}
{% for i in post %}
<h2>{{post.title}}</h2>
<p class="meta">{{post.date}}</p>
{% endfor %}
{% endif %}
{% endblock %}
and my urls.py:
from django.conf.urls import include, url, patterns
urlpatterns = patterns('blog_static.views',
(r'^postlist/', 'list'),
)
I have two questions:
Can you figure out where I am going wrong in this code?
Are there any alternative ways that I may go about doing this? This may be an inefficient way of listing documents from a local folder, so I am open to other options as well.
Any sort of help would be appreciated. Thanks!
It sounds like you are already familiar with, and could execute this using ListView. You can use ListView without a model - as referenced in various parts of the documentation ("is not necessarily a queryset"):
https://docs.djangoproject.com/en/1.8/ref/class-based-views/mixins-multiple-object/#django.views.generic.list.MultipleObjectMixin.get_queryset
Get the list of items for this view. This must be an iterable and may be a queryset (in which queryset-specific behavior will be enabled).
Therefore you should be able to do the following:
class MyListView(generic.ListView):
template_name = 'foobar.html'
def get_queryset(self):
return [1, 2, 3]
What's wrong with your example... it's the fact you're referencing post in your inner for loop as opposed to the i that you defined as the actual post.
It's confusing because you rename the python posts variable to post in the template context, then iterate over it as i.
posts in your template context is just a list, and has no attributes, keys, etc., named post.title.
post is array of dict objects. So
{% extends 'base.html' %}
{% block content %}
{% if post %}
{% for i in post %}
<h2>{{i.title}}</h2>
<p class="meta">{{i.date}}</p>
{% endfor %}
{% endif %}
{% endblock %}

search form with django+python

I have just started to do a website with django + python and I want to implement a search form to be able to search on all my database objects. What I want is; when I write for an example S I want the search field to display all my objects that starts with the letter S in a list, just like the Tags field below on this site.
Does anyone have a good ide to implement this with django?
For a decent django search implementation, I would recommend looking at djapian. However, for what you are doing, I would recommend a query using the ISTARTSWITH parameter. Consider the following:
views.py
def search(req):
if req.GET:
search_term = req.GET['term']
results = ModelToSearch.objects.filter(field__istartswith=search_term)
return render_to_response('search.html', {'results': results})
return render_to_response('search.html', {})
search.html
<html>
<body>
<form>
<input name='S'>
</form>
{% if results %}
Found the following items:
<ol>
{% for result in results %}
<li>{{result}}</li>
{% endfor %}
</ol>
{% endif %}
</body>
</html>

Categories

Resources