Django template not showing database contents - django

This is for certain a newbie mistake, I have googled for plenty of hours now, not finding a working solution. I assume part due to not being sure what to search for exactly.
I am working on a tiny blog application, I have models for user, post, blogComment and that is all.
I have written views for blogIndex and for blogPost, that is a listing of all posts and a listing of specific posts.
The blogIndex is working in the view that it belongs to, it shows {{ post.content }} {{ post.author.firstname }} and so on with no problem.
The blogPost is however not. The view looks like this:
def blogPost(request, postID):
blogPost = post.objects.get(id=postID)
return render_to_response("blog_post.html", {"post":post})
The blog_post.html looks like this:
title: {{ post.title }}</br>
content: {{ post.content }}</br>
datetime: {{ post.datetime }}</br>
author: {{ post.author.first_name }} {{ post.author.last_name }}</br></br>
{% for comment in post.blogcomment_set.all %}
Comment.firstName: {{comment.firstName}}</br>
{{comment.lastName}}</br>
{{comment.email}}</br>
{{comment.datetime}}</br>
{{comment.content}}</br>
{% endfor %}
With the same code in blog_index.html, I get a proper listing of title, content and so on.
This is from urls.py:
url(r'^blog/$', blogIndex),
url(r'^blog/(?P<postID>\d+)$', blogPost),
I suspect something is wrong with the regex?
I suspect something is more likely wrong with the view?
This is the view for blogIndex, which is working, but maybe helps with answers:
def blogIndex(request):
posts = post.objects.all()
return render_to_response("blog_index.html", {"posts":posts})
This, finally, is the code in blog_index.html:
{% for post in posts %}
<h3>{{ post.title }}</h3>
{{ post.content }}
<p>Posted by: {{ post.author.first_name }} {{ post.author.last_name }}<br /> At:
{{ post.datetime }}</p>
<p><strong>Comments: </strong><br />
{% for comment in post.blogcomment_set.all %}
By: {{ comment.firstname }}<br />
Title: {{ comment.title }},<br />
Content: {{ comment.content }}<br />
Date: {{ comment.datetime }}</p>
{% endfor %}
{% endfor %}
Links to possible solutions or pointing me on the nose for being narrow sighted are both welcome input.

def blogPost(request, postID):
blogPost = post.objects.get(id=postID)
return render_to_response("blog_post.html", {"post":post})
Should be:
def blogPost(request, postID):
blogPost = post.objects.get(id=postID)
return render_to_response("blog_post.html", {"post":blogPost})

Related

How to paginate multiple queries in a single function-based-view or class-based-view in django?

I have a search function that queries multiple models. I have the expected results displayed in a html template and so far all is fine. The problem is that I want to paginate the results using django's built in Pagination class. Pagination with multiple models is where I'm now stuck. I have other class based views working well paginating single models.
def search_results(request):
if request.method == 'POST':
searched = request.POST['searched']
books = Book.objects.filter(description__icontains=searched,
title__icontains=searched).order_by('-id')
sermons = Sermon.objects.filter(description__icontains=searched,
title__icontains=searched).order_by('-id')
other_sermons = SermonsByOtherFathers.objects.filter(description__icontains=searched,
title__icontains=searched).order_by('id')
other_books = BooksByOtherFathers.objects.filter(description__icontains=searched,
title__icontains=searched).order_by('-id')
context = {
'searched': searched,
'sermons': sermons,
'other_sermons': other_sermons,
'books': books,
'other_books': other_books,
}
if searched == "":
return HttpResponse('Please type something in the search input.')
return render(request, "search_results.html", context)
This is a simplified version of my html template.
{% for book in books %}
<tr>
<td>
{{ book.title }}
<p> {{book.author}} </p>
<p> {{ book.category }} </p>
<p> {{ book.description }} </p>
</td>
</tr>
{% endfor %}
<-- ...and the same loops goes for the rest of the other querysets. -->
{% for book in other_books %}
<-- code here -->
{% endfor %}
{% for sermon in sermons %}
<-- code here -->
{% endfor %}
{% for sermon in other_sermons %}
<-- code here -->
{% endfor %}
Any help with the django multiple-model pagination part will be appreciated.

Django ListView works but DetailView not displaying Model Data

I am helping my daughter with her computing Project for school. It is a simple generic forum type application.
She has a ListView for a model which works fine:
{% extends 'users/main.html' %}
<!-- Here is where our content will begin -->
{% block content %}
<h1>This is posts.html!</h1>
<br/>
{% for obj in object_list %}
<h2>{{ obj.topic }}</h2>
{{ obj.date_posted }}
<br/>
{{ obj.content }}
<br/>
Author: {{ obj.author }}
<br/><br/>
{% endfor %}
{% endblock %}
She then added a DetailView which is simply the same code with the loop removed:
{% extends 'users/main.html' %}
<!-- Here is where our content will begin -->
{% block content %}
<h1>This is posts.html!</h1>
<br/>
{{ obj.id }}
<h2>{{ obj.topic }}</h2>
{{ obj.date_posted }}
<br/>
{{ obj.content }}
<br/>
Author: {{ obj.author }}
<br/><br/>
{% endblock %}
This is then called with a '....post/1/' (post id = 1 does exist (checked via DB Browser and in the ListView) and the path and naming of the template is correct.
Frustratingly, this displays the page but not the details inside the django temp language brackets (object.topic etc)!
When I look at the page source for the section dealing with the detail, I get:
screenshot of page
and the source code looks like so:
<h1>This is posts.html!</h1>
<br/>
<h2></h2>
<br/>
<br/>
Author:
<br/><br/
It is simply ignoring the bracketed templating code - any ideas?
Django DetailView returns 'object' inside context by default.
If you did not change 'context_object_name' variable, then use {{object}} instead of {{obj}}
<h1>This is posts.html!</h1>
<br/>
{{ object.id }}
<h2>{{ object.topic }}</h2>
{{ object.date_posted }}
<br/>
{{ object.content }}
<br/>
Author: {{ object.author }}
<br/><br/>
Really thanks a lot for all of this.
I corrected my template to include 'object' and made it march all conventions to avoid having to send in context information.
It still wouldn't work.
I rebooted localhost repeatedly because it all made no sense.
Finally, I rebooted my daughters PC and immediately, everything worked.
A lesson learned and as a dad helping a 17 year old daughter who did his Computer Science degree 40(!) years ago, another lesson in how complicated and challenging understanding a framework can be.
I must say - it has been fun.
Thanks again,
Howard.

Django: How to add comments under post

I have trouble adding comments under my posts on the website I'm creating using Django.
This is my story.html file, which is supposed to show the story title, the story itself, all the comments of the story and give users the ability to add a new comment. Although the form is shown, it is not usable. Even though I have added comments to the stories manually through admin, none of them is shown.
{% extends "pinkrubies/base.html" %}
{% block content %}
<div class="post-preview">
<h2 class="post-title"> {{ story.title }}</h2>
<p class="post-subtitle">
{{ story.story }}
</p>
</div>
<div class="post-preview">
{% for com in latest_comments %}
<div class="post-preview">
<p class="post-subtitle"> {{ comment.com }} </p>
</div>
{% endfor %}
</div>
{% if user_id %}
<div class="post-preview">
<form action="{% url 'pinkrubies:story' user.id story.id %}" method="post">
{% csrf_token %}
<div class="form-group">
<p class="post-title">
Comments
</p>
<textarea id="text" name="text"class="form-control" placeholder="Comment" rows="4">{{ comment.com }}
</textarea>
</div>
<button type="submit" class="btn btn-primary"> Submit </button>
</form>
</div>
{% else %}
<p class="post-meta">You must have an account to comment. Log in or Register</p>
{% endif %}
{% endblock %}
views.py
def story_view(request, user_id, story_id):
latest_comments = Comment.objects.order_by('-date')
if story_id is not None:
story = get_object_or_404(Story, pk=story_id)
else:
story = Story()
story.user_id = user_id
if request.method == 'POST':
story.title = request.post.get('title')
story.story = request.post.get('story')
story.date = timezone.now()
story.save()
return HttpResponseRedirect(reverse('pinkrubies:story', args=(user_id,)))
else:
context = {
'user_id': user_id,
'story_id': story_id,
'title': story.title,
'story': story,
'comments': story.comments,
'latest_comments': latest_comments
}
return render(request, 'pinkrubies/story.html', context)
def comment_view(request, comment, user_id):
latest_comments = Comment.objects.order_by('-date')
if request.method == 'POST':
comment.com = request.POST['com']
comment.date = timezone.now()
comment.save()
return HttpResponseRedirect(reverse('pinkrubies:story', args=(user_id,)))
else:
context = {'latest_comments': latest_comments}
return render(request, 'pinkrubies/story.html', context)
I am aware I have added the "latest_comments" in both views, I did that to see if any of it works and it doesn't. I'm not even sure that the comment_view is needed.
Also, when I try to submit a comment, this error is thrown:
AttributeError: 'WSGIRequest' object has no attribute 'post'
in story_view story.title = request.post.get('title')
Any help is welcome!
Thank you !!!
First of all, if you want to get something from POST, you should use request.POST.get('title'); although I would rather use a Form and let it handle the request.
At a first glance, this:
{% for com in latest_comments %}
<div class="post-preview">
<p class="post-subtitle"> {{ comment.com }} </p>
</div>
{% endfor %}
Sould be
{% for comment in latest_comments %}
<div class="post-preview">
<p class="post-subtitle"> {{ comment.com }} </p>
</div>
{% endfor %}
In your code, you're using com to iterate through latest_comments, yet you try to use comment to access com attribute (not sure how your Comment model looks like though)
It's accessed via request.POST. WSGIRequest object does not have a post field it has POST field.
Also, you are not sending the fields you are attempting to read from request.
...
story.title = request.POST.get('title')
story.story = request.POST.get('story')
...
only field you are sending is called text and it should be accessed like this
text = request.POST.get('text')
also template has more errors please check your code once again.

Django nested QuerySet yielding nothing

I am using Django 1.8 with Postgres 9.2 on a Windows 8 machine.
I have two pieces of nearly identical code from two of my projects. One works and the other doesn't.
Here's the code that works:
# views.py
from django.shortcuts import render
from models import Artist, Track
def music(request):
artists = Artist.objects.all().order_by('orderName')
artistTrackCollections = []
for artist in artists:
artist.tracks = Track.objects.filter(artist=artist).order_by('order')
artistTrackCollections.append(artist)
return render(request, 'music.html', {'artistTrackCollections': artistTrackCollections,})
And the relevant template code:
{% for artist in artistTrackCollections %}
<dl>
<dt>
{% if artist.website %}
<h2>{{ artist.name }}</h2>
{% else %}
<h2>{{ artist.name }}</h2>
{% endif %}
</dt>
<dd>
<ul>
{% for track in artist.tracks %}
<li>“{{ track.title }}”
<i>({{ track.album.title }})</i>
{% endfor %}
</ul>
</dd>
</dl>
{% endfor %}
Now here's pretty much the exact same code from a different project of mine that doesn't work anymore:
def index(request):
productList = PartModel.objects.filter(isBuild=True, isActive=True).order_by('name')
productCollection = []
for product in productList:
product.part_list = product.buildpart.all().order_by('family__type')[:5]
productCollection.append(product)
return render(request, 'index.html', { 'productCollection': productCollection, })
and its corresponding template:
{% for product in productCollection %}
<p>{{ product.name }}
<p>${{ product.price }}
<ul>
{% for part in product.part_list %}
<li>{{ part.family.type.name }} | {{ part.name }}
{% endfor %}
</ul>
{% endfor %}
This code used to work but now it doesn't. In the code that works I succeed in going through each artist and attaching that artist's tracks. In the code that fails I try to go through each PartModel instance that is a build and get that PartModel instance's corresponding parts. They are identical as far as I can tell. productCollection gets populated but the part_list data for some reason is blank. This leads me to believe the problem is with this line:
product.part_list = product.buildpart.all().order_by('family__type')[:5]
But I cannot discern the difference from this line:
artist.tracks = Track.objects.filter(artist=artist).order_by('order')
Thanks in advance for any help!

fetch variables in django templates

I am new to django .
I am facing a small problem but unable to solve it.
In my template when I try to access any variable using {{ }} but it returns blank while displaying something as detailview.whereas it works fine in listview.
CODE:urls.py
urlpatterns = patterns('',
url(r'^$', ListView.as_view(
queryset=Profile.objects.all().order_by("First_Name"),
template_name="STUDENT_REGISTRATION.html")),
url(r'^(?P<pk>\d+)/$',DetailView.as_view(
model=Profile,
template_name="Profile.html")),
TEMPLATE:
{%extends "base.html" %}
{% block content %}
<h2>Registration No. :- {{ Profile.Registration_No }} <br>
Full Name : {{ Profile.First_Name }} {{ Profile.Last_Name }} </h2>
<div class="Profile_meta">
{{ Profile.Date_of_Birth}}
</div>
<div class="Profile_body">
{{ Profile.Permanent_Address|safe|linebreaks }}
</div>
{%endblock%}
Plz help..
You should refer to your Profile instance as:
{{ object.First_Name }} {{ object.Last_Name }}
By the way, take a look at PEP8, try to keep CamelCaseNames for class names and underscores_names for instances. It will make your code easier to read.