Can't iterate from BlogPost object in my template (Django) - python

I can't iterate through BlogPost object in my templates. Nothing is showing up for some reason. I probably forgot something. In the shell I can obtain the objects without any problem. So something is wrong, and I can't figure out what.
views.py:
def latest_posts(request):
latest_posts = BlogPost.objects.all().filter(site_id=1)[:50]
render(request, (settings.PROJECT_ROOT + "/main/templates/includes/latest_posts.html"), {"latest_posts": latest_posts})
latest_posts.html:
{% load pages_tags mezzanine_tags i18n accounts_tags %}
<div class="panel panel-default" >
<div class="panel-heading">
<h3 class="panel-title">{% trans "Latest Posts" %}</h3>
</div>
<div class="panel-body" style="padding:0;border:0px;">
{% for lp in latest_posts %}
<ul class="list-group-latest-posts">
<li class="list-group-item-latest-posts">
<img class="media-object left" src="#" width="40" height="40" alt="#">
<p>{{ lp.title }}<br><span class="latest-post-name">user_name</span><span class="latest-post-divider"> - </span><span class="latest-post-time">6 Hours Ago</span></p>
</li>
</ul>
{% endfor %}
</div>
</div>
This is my structure. In base.html:
{% if '/' in request.path %}
{% else %}
{% include "includes/sidebar.html" %}
{% endif %}
sidebar.html:
<div class="col-md-4 right">
{% include 'includes/latest_posts.html' %}
</div>
In my urls.py:
url("^$", direct_to_template, {"template": "index.html"}, name="home"),

You're page is loaded from a different view called direct_to_template that has nothing to do with the latest_posts view so it will never find its context data.
So now 1 of two things needs to happen, either you just consume the code from latest_posts re: the context data into that other view and include it in that context. Or you make a url to point to that page
from views import latest_posts
url("^latest_posts$", latest_posts, name="latest_posts"),
Now this will get you the posts showing from the url /latest_posts, but it probably doesn't look very pretty, it could be an option to have the latest_posts view still load the base.html template which will make it look more like you expect, although a browse through the documentation on template inheritance may help more

Related

Why does the NoReverseMatch error pop up when trying to paginate my django website?

I have a list of data from my models that I would like to paginate as it looks flooded on one singular page and it generally takes a longer time for the page to load. However, when I tried to use a paginating method, it doesn't seem to work in my code.
What I've already done for my code is:
.../clubs/views.py
class ClubListView(generic.ListView):
model = Club
paginate_by = 6
.../clubs/urls.py
from django.urls import path
from . import views
app_name = "clubs"
urlpatterns = [
path('', views.ClubListView.as_view(), name="club-list"),
path('<int:pk>/', views.ClubDetailView.as_view(), name="club-detail"),
]
.../clubs/club_list.html
{% block group_content %}
<hr>
{% comment %} Complete making group display. {% endcomment %}
<p></p>
<div class="col-md-8">
<div class="container">
{% for club in club_list %}
<a class="list-group-item" href="{{ club.get_absolute_url }}">
<h3 class="title list-group-item-heading">{{ club.name }}</h3>
<span>{{ club.slogan|safe }}</span>
</a>
<p></p>
<br>
{% endfor %}
</div>
</div>
{% endblock %}
{% block pagination %}
{% if page_obj.has_previous %}
<a href="{% url 'club-list' page_obj.previous_page_number %}">
Previous Page
</a>
{% endif%}
{% if page_obj.has_next %}
<a href="{% url 'club-list' page_obj.next_page_number %}">
Next Page
</a>
{% endif%}
{% endblock %}
However, it still gives me the error of NoReverseMatch of 'club-list' in my html page even though it is given from the urls.py file. I'm not sure if I don't understand where the issue is coming from.
You are passing the next page number/prev page number as part of the {% url %} function which creates the path, however your URLS.py isn't expecting it as part of the URL path. eg, you don't have a urlpattern for listview/12/.
For a list view, by default next and prev pages numbers gets passed as part of the querystring rather than the path,eg,
/listview?page=12
so your template should look more like (from the docs)
{% block pagination %}
{% if page_obj.has_previous %}
« first
previous
{% endif %}
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
{% if page_obj.has_next %}
next
last »
{% endif %}
{% endblock %}

Django Template--Conditional Based on The Current URL Path

I'm trying to exclude some content from the 'Blog' section of my site and would like to exclude this info on any paths that start with /blog, which would include the main /blog page and any other associated pages including blog/<blog-post> etc. I've looked at this post and tried some of the advice mentioned here but can't exactly get it to work. Here are my two blog URLs:
url(r'^$', BlogListView.as_view(), name='blog'),
url(r'^(?P<slug>[\w-]+)/$', blog_post, name='blog_post')
and what I've tried (unsuccessfully) in my django template:
{% url 'blog:blog_post' slug=slug as the_url %}
{% if request.path == the_url %}
<div> </div>
{% else %}
<div class="container">
<div class="nav-2">
<ul class="nav nav-pills">
{% block side_block %}
{% get_category_list %}
{% endblock %}
</ul>
</div>
</div>
{% endif %}
Ok, i figured it out thanks to this post
{% if '/blog/' in request.path %}DO SOMETHING HERE{% endif %}

Django 1.8 calls to database in html code

long-time lurker for this website, but I finally decided to join the community.
I have a quick question on some of my code. I took a job this year for my university developing a website for the journalist department. The website was being built the previous year by another student using Django 1.8, python 2, and everything else that comes with that. I knew a decent amount about these languages, and I have learned a lot testing out different methods for hours on end. However, there is one thing I am having trouble with that I have researched for forever.
Basically, for my website, I have different "sections" for different pages of articles. These articles have many traits. One trait is called "section" and this section has the names of the pages. So for example:
One page is named "look". I can call my code and display all of my featured_articles. HOWEVER, I am trying to only display the articles where the name of the section equals "look".
Here is my current code. Any ideas? I have tried many things but I can't get it to work properly. For loops, if statements, different HTML processes, different pages in django, etc...
{% for article, section in featured_articles %}
<div class="media panel panel-default">
<div class="panel-body">
<div class="media-left">
<a href="articles/{{ article.url }}">
<img class="media-object thumbnail-featured"
src="{{ article.image }}">
</a>
</div>
<div class="media-body">
<a href="articles/{{ article.url }}">
<h3 class="media-heading">{{ article.title }}</h3>
</a>
<!-- TODO figure out how to iterate through the authors field, manytomany -->
{% for contributor in article.authors.all %}
<p>{{ section.name }} |
{{contributor}}</p>
{% endfor %}
<p>{{article.preview}}</p>
</div>
</div>
</div>
{% endfor %}
Thank you for any help!!
Overall, it is a not such a good idea. You are sending all data to the template engine and doing the filtering there?
Why not filter it in the view function / view class and then return that data inside a template variable and then render in the front end?
def detail(request, poll_id):
filtered_data = .......objects.get(name='look')
return render(request, 'polls/detail.html', {'look_data': filtered_data})
{% for article, section in look_data %}
<div class="media panel panel-default">
.... blah blah blah
</div>
{% endfor %}
As I understand, you just need to add if statement:
{% for article, section in featured_articles %}
{% if section.name == 'look' %}
<div class="media panel panel-default">
<div class="panel-body">
<div class="media-left">
<a href="articles/{{ article.url }}">
<img class="media-object thumbnail-featured"
src="{{ article.image }}">
</a>
</div>
<div class="media-body">
<a href="articles/{{ article.url }}">
<h3 class="media-heading">{{ article.title }}</h3>
</a>
<!-- TODO figure out how to iterate through the authors field, manytomany -->
{% for contributor in article.authors.all %}
<p>{{ section.name }} |
{{ contributor }} </p>
{% endfor %}
<p>{{article.preview}}</p>
</div>
</div>
</div>
{% endif %}
{% endfor %}

Template not rendering properly with if user.is_authenticated for Django

I'm trying to incorporate an template tag/inclusion tag into my sidebar for the site. The main section of the page updates properly when I put:
{% if user.is_authenticated %}
<h1> Hello {{ user.username }}
{% else %}
<h1> Hello </h1>
{% endif %}
When I try to use the same principle in my template tag/sidebar, it seems to ignore user.is_authenticated and will always show 'login' and 'register', when it should be just showing 'logout'.
The body of the html (main index page):
{% load Kappa_extras %}
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-2" id="side_section">
{% block sidebar %}
{% get_game_list %}
{% endblock %}
</div>
<!--Main section-->
<div class="col-sm-10" id="main_section">
{% block body %}
{% endblock %}
</div>
</div>
</div>
The get_game_list function from 'Kappa_extras':
from django import template
from Kappa.models import Game, Game_Page
from django.contrib.auth.models import User
register = template.Library()
#register.inclusion_tag('Kappa/sidebar.html')
def get_game_list():
return {'game_list': Game.objects.all()}
and the 'Kappa/sidebar.html':
<div id="side_default_list">
<ul class="nav">
<li>Kappa</li>
{% if user.is_authenticated %}
<li>Log Out</li>
{% else %}
<li>Log In</li>
<li>Register</li>
{% endif %}
</div>
I checked a few older inquires though none of them are working properly. I tried putting request into def get_game_list(request): but it just said did not receive value for the argument. How do I get the sidebar to update properly when user.is_authenticated?
You need to pass the user to your inclusion tag.
#register.inclusion_tag('Kappa/sidebar.html')
def get_game_list(user):
return {'game_list': Game.objects.all(), 'user': user}
Then in your template, call the tag with
{% get_game_list user %}
Alternatively, you can set takes_context=True in your inclusion tag, so that you can access the user from the template context.
#register.inclusion_tag('Kappa/sidebar.html', takes_context=True)
def get_game_list(context):
return {'game_list': Game.objects.all(), 'user': context['user']}
In this case, you don't need to pass the user to the template tag any more.
{% get_game_list %}
See the docs for more information and other examples.

Django doesn't seem to detect my login.html, block problem?

I'm creating a web app with django 1.2.4.
I am using contrib.auth.views.login, I have followed every step but it seems I have forgotten something cause I don't see the login form. Here is my folder structure:
/templates/
base.html
/myapp/
object_list.html
...
/registration/
login.html
...and here is my login.html:
{% extends "base.html" %}
{% block mylogin %}
<div class="horizontal">
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form action="{% url django.contrib.auth.views.login %}" method="post">
{% csrf_token %}
<div class="login_box">
<div class="login_text">{{ form.username.label_tag }}</div><div class="login_input">{{ form.username }}</div>
<div class="password_text">{{ form.password.label_tag }}</div><div class="password_input">{{ form.password }}</div>
<input id="button_login" type="submit" value="" />
</div>
</form>
</div>
{% endblock %}
...and in my base.html I have:
<div id="some_div">
{% block mylogin %} {% endblock %}
</div>
I have a basestyle.css included in base.html and the other templates inherit correctly too... it seems to be a block problem...
Any solution??
Thnak you
Instead of inserting of a block I used the include tag in base.html, just like this:
{% include "registration/login.html" %}
If you’d prefer not to call default (django provided) template registration/login.html, you can pass the template_name parameter via the extra arguments to the view in your URLconf.
For example, this URLconf line would use myapp/login.html instead:
(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}),
Reference : Django official documentation
It solves my problem. Hope this works for others.

Categories