How display a bucle for 'post' in a booststrap carousel? - django

I'm new to django and i'm doing my first project.
my question is how display my posts in a bootstrap carrousel?
I used: Boostrap 4.3.1
Django 2.2
this is my code:
base.html
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<body>
...
</body>
</head>
</html>
post_list.html
{% extends 'blog/base.html' %}
{% block content %}
<br>
{% for post in posts %}
<div class="post">
<div class="date">
<p>published: {{ post.published_date }}</p>
</div>
<h1>{{ post.title }} </h1>
<h5 class="badge badge-secondary">by {{ post.author }}</h5>
<p>{{ post.text|linebreaksbr }}</p>
Comments: {{ post.comments.count }}
</div>
{% endfor %}
{% endblock %}
models.py
from django.utils import timezone
from django.contrib.gis.db import models
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.publish_date = timezone.now()
self.save()
def __str__(self):
return self.title
urls.py
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
]
and views.py
from django.shortcuts import render
def post_list(request):
posts =Post.objects.filter(published_date__lte=timezone.now()).order_by('created_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
posts = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': posts})
I tried with this code but it doesn´t work:
<div class="carousel-inner">
{% for post in posts|slice:":3" %}
{% if forloop.first %}
<div class="active item">
{% else %}
<div class="item">
{% endif %}
<blockquote>
<p>{{ post.title }}</p>
</blockquote>
<label>{{ post.text }}</label>
</div>
{% endfor %}
</div>
I want it to look like this without the img:
My template looks now:

Related

Django- Template not found

I can't seem to get my delete, edit and add review functionality working. The errors come as soon as I try to navigate to the urls I have set up. When I try and add a new review using my link on the reviews page I get the below message:
TemplateDoesNotExist at /reviews/add
I don't understand why because I have linked the url above to the template, which I have created.
The issue I have with my edit/delete views is that the url it searches for when I click the button is just /edit/ or /delete/ rather than reviews/edit/int:pk or reviews/delete/int:pk as per my urls.
I have pasted my code below, any help would be much appreciated! I have the feeling I am going to kick myself when I realise!
reviews.html:
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid home-container">
<div class="row align-items-center">
<div class="col-sm-12 text-center mt-4">
<h2><strong>Reviews</strong></h2>
</div>
</div>
{% for review in reviews %}
<hr class="hr-1">
<div class="row featurette">
<div class="col-sm-12">
<h2 class="featurette-heading">{{ review.title }}</h2>
<p class="lead">{{ review.content }}</p>
<div class="row justify-content-between mx-1">
<p>By: {{ review.user }}</p>
<p>Created on: {{ review.created }}</p>
<p>Last Updated: {{ review.updated }}</p>
</div>
<!-- Add user authentication if -->
<div class="text-center">
<a href="edit/{{ review.id }}" class="mx-2">
<button class="positive-button mb-2">Edit</button></a>
<a href="delete/{{ review.id }}" class="mx-2 mb-2">
<button class="negative-button">Delete</button></a>
</div>
</div>
</div>
{% endfor %}
<div class="row">
<div class="col-sm-12 text-center py-4">
{% if user.is_authenticated %}
<a href="{% url 'home:add_review' %}">
<button class="positive-button-lg">Add a review</button>
</a>
{% else %}
<p>If you would like to add your own review, please login or sign up if you haven't already!</p>
{% endif %}
</div>
</div>
</div>
{% endblock %}
add_review.html:
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<form method="post" style="margin-top: 1.3em;">
{{ review_form }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
</div>
</div>
{% endblock %}
views.py:
from django.shortcuts import render
from django.views import View
from django.urls import reverse_lazy
from django.views.generic import UpdateView, DeleteView
from .models import Reviews
from .forms import ReviewForm
def home(request):
''' Returns the home page.'''
return render(request, 'home/index.html')
def reviews(request):
''' Returns the reviews page.'''
serialized_reviews = []
reviews = Reviews.objects.all()
for review in reviews:
serialized_reviews.append({
"title": review.title,
"content": review.content,
"user": review.user,
"created": review.created,
"updated": review.updated,
})
context = {
"reviews": serialized_reviews
}
print(serialized_reviews)
return render(request, 'home/reviews.html', context)
class AddReview(View):
'''View which allows the user to add a new review.'''
def get(self, request, *args, **kwargs):
review = Reviews
review_form = ReviewForm
context = {
'review': review,
'review_form': review_form,
'user': review.user,
'title': review.title,
'content': review.content,
}
return render(request, 'add_review.html', context)
def post(self, request, *args, **kwargs):
review_form = ReviewForm(data=request.POST)
if review_form.is_valid():
obj = review_form.save(commit=False)
obj.user = request.user
obj.save()
return redirect("home:reviews")
class DeleteReview(DeleteView):
'''View which allows the user to delete the selected review.'''
model = Reviews
template_name = 'delete_review.html'
success_url = reverse_lazy('reviews')
class EditReview(UpdateView):
'''View which allows the user to edit the selected review.'''
model = Reviews
template_name = 'edit_review.html'
fields = ['title', 'content']
urls.py:
from django.urls import path
from . import views
app_name = 'home'
urlpatterns = [
path('', views.home, name='home'),
path('reviews', views.reviews, name='reviews'),
path('reviews/add', views.AddReview.as_view(), name='add_review'),
path('reviews/delete/<int:pk>', views.DeleteReview.as_view(), name='delete_review'),
path('reviews/edit/<int:pk>', views.EditReview.as_view(), name='edit_review'),
]
The main difference is my app name, which is 'core'. Also, I forgot to add the content field to the model, but that is easily done, the form will just handle it as soon as you do the migration. (except on list.html)
models.py
from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone
class Reviews(models.Model):
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
title = models.CharField(max_length=128)
created_at = models.DateTimeField(auto_now_add=timezone.now())
updated_at = models.DateTimeField(auto_now=timezone.now())
forms.py
from django import forms
from core.models import Reviews
class ReviewsForm(forms.ModelForm):
class Meta:
model = Reviews
fields = '__all__'
views.py
from core.models import Reviews
from core.forms import ReviewsForm
from django.shortcuts import render, redirect
def list_reviews(request):
reviews = Reviews.objects.all()
context = {
"reviews": reviews
}
return render(request, 'reviews/list.html', context)
def add_review(request):
if request.method == 'POST':
form = ReviewsForm(request.POST)
if form.is_valid():
form.save()
return redirect('/reviews/')
else:
form = ReviewsForm()
context = {
'form': form
}
return render(request, 'reviews/detail.html', context)
def edit_review(request, pk):
if request.method == 'POST':
form = ReviewsForm(request.POST)
if form.is_valid():
obj = Reviews.objects.get(id=pk)
obj.title = form.cleaned_data['title']
obj.user = form.cleaned_data['user']
obj.save()
return redirect('/reviews/')
else:
obj = Reviews.objects.get(id=pk)
form = ReviewsForm(instance=obj)
context = {
'form': form
}
return render(request, 'reviews/detail.html', context)
def delete_review(request, pk):
obj = Reviews.objects.get(id=pk)
obj.delete()
return redirect('/reviews/')
urls.py
from django.urls import path
import core.views as views
app_name = 'core'
urlpatterns = [
path('reviews/', views.list_reviews, name='list-reviews'),
path('reviews/add', views.add_review, name='add-review'),
path('reviews/edit/<int:pk>/', views.edit_review, name='edit-review'),
path('reviews/delete/<int:pk>/', views.delete_review, name='delete-review'),
]
list.html
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid home-container">
<div class="row align-items-center">
<div class="col-sm-12 text-center mt-4">
<h2><strong>Reviews</strong></h2>
</div>
</div>
{% for review in reviews %}
<hr class="hr-1">
<div class="row featurette">
<div class="col-sm-12">
<h2 class="featurette-heading">{{ review.title }}</h2>
<p class="lead">{{ review.content }}</p>
<div class="row justify-content-between mx-1">
<p>By: {{ review.user }}</p>
<p>Created on: {{ review.created_at }}</p>
<p>Last Updated: {{ review.updated_at }}</p>
</div>
<!-- Add user authentication if -->
<div class="text-center">
<a href="{% url 'core:edit-review' pk=review.id %}" class="mx-2">
<button class="positive-button mb-2">Edit</button></a>
<a href="{% url 'core:delete-review' pk=review.id %}" class="mx-2 mb-2">
<button class="negative-button">Delete</button></a>
</div>
</div>
</div>
{% endfor %}
<div class="row">
<div class="col-sm-12 text-center py-4">
{% if user.is_authenticated %}
<a href="{% url 'core:add-review' %}">
<button class="positive-button-lg">Add a review</button>
</a>
{% else %}
<p>If you would like to add your own review, please login or sign up if you haven't already!</p>
{% endif %}
</div>
</div>
</div>
{% endblock %}
detail.html
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<form method="post" style="margin-top: 1.3em;">
{% csrf_token %}
<table>
{{ form }}
</table>
<button type="submit" class="btn btn-primary btn-lg">Save</button>
</form>
</div>
</div>
{% endblock %}
According to your urls, It is a review/edit/<int:pk>.
So you must add same thing in href tag.
Change this:
<a href="edit/{{ review.id }}"
To this:
<a href="review/edit/{{ review.id }}"
That's why you are getting that error
I've fixed it, firstly the path in my add_review view was wrong, which I have amended and it now works (thanks Ivan).
I also was not actually bringing the ID through on my 'reviews' view in the first place, so when following the links on my edit and review buttons, it didn't know what I meant by 'id', as I hadn't specified what that was in the view context.
Thanks for the help all!
I think you're writing in your urls the wrong way, like this below your div text-center:
<a href="edit/{{ review.id }}" class="mx-2">
It should be:
<a href="{% url 'yourappname:edit' review.id %}">

How to link two model in django and fetch data from them in template

I create two model name subject and section if I create a model name maths I want to create some section in it which is one to one so I am trying to load the page of a section acc to the subject like I click on maths link only the section which is relate to math open no other section open I think you understand so here is my code
my models.py
class Subject(models.Model):
name = models.CharField(max_length=80, blank=False,)
thumbnail = models.ImageField(upload_to='subject thumbnail', blank = False)
total_Section = models.FloatField(default='0')
joined_date = models.DateTimeField(default=timezone.now,editable=False)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Section(models.Model):
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
sub_section = models.CharField(max_length=500, blank=True)
title = models.CharField(max_length=5000, blank=False)
teacher = models.CharField(max_length=500, blank=False)
file = models.FileField(upload_to='section_vedios', blank=False)
price = models.FloatField(blank=False)
content_duration = models.DurationField(blank=False)
joined_date = models.DateTimeField(default=timezone.now,editable=False)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
my views.py for subject
#login_required
def home(request):
subject_list = Subject.objects.all()
return render (request, 'home.html', {'subject_list': subject_list })
my views.py for sections
#login_required
def sections(request):
return render (request, 'sections.html',)
my html for subject it worked
<ul>
{% for subject in subject_list %}
<li class="sub"> <a name='thumb' class="thumb" href="{% url 'subjects:section' %}"><img class="thumbnail" src="{{ subject.thumbnail.url }}" alt="">
<span><strong> {{ subject.name }} </strong> </span> </a>
<p>No of Section : {{ subject.total_section }} </p> </li>
{% endfor %}
</ul>
my html for viewing section according to subject by clicking link it is not showing anything
<li class="sub"> <a name='thumb' class="thumb" href="#">
<span><strong> {{ subject.section.title }} </strong> </span> </a>
<p>Name: {{ subject.section.teacher }} </p> {{ subject.section.price }} </li>
</div>
my urls.py for home html in which subject are rendering
urlpatterns = [
path('Register/',views.register,name='register'),
path('', views.my_login, name='login'),
path('logout/',views.user_logout,name='logout'),
path('SectionWise/',views.home,name='home'),
path('edit-profile/',views.edit_profile,name='edit')
]
my urls.py for section
urlpatterns = [
path('Section/', views.sections, name='section'),
path('add_section/',views.add_sections,name='add_section')
]
I tried to use above method like for subject but in every link it shows all the section no matter which subject link you are clicking
adding as asked
urls.py
urlpatterns = [
path('section/<int:section_id>/', views.sections, name='section'),
path('add_section/',views.add_sections,name='add_section')
]
my home.html
{% for subject in subject_list %}
<a href="{% url 'subjects:section' subject.section.id %}">
<div class="card" style="width: 18rem;">
<img src="{{ subject.thumbnail.url }}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{subject.id}} {{ subject.name }}</h5>
<p class="card-text">{{ subject.about }}</p>
<hr>
<p class="number" > No of Section:<strong> {{ subject.total_Section }}</strong></p>
<p class="last"> Last update:<strong> {{ subject.update_at }}</strong></p>
</div>
</div>
</a>
{% endfor %}
In your models.py, change your subject in Section class to include the related_name attribute
class Section(models.Model):
subject = models.ForeignKey(Subject, related_name="section" on_delete=models.CASCADE)
# .... the rest of your fields
Then edit your sections in views to be
from django.shortcuts import get_object_or_404
#login_required
def sections(request, subject_id):
subject = get_object_or_404(Subject, pk=subject_id) # retrieve the subject
section_list = subject.section.all() # get the sections related to the subject
print(section_list)
return render (request, 'sections.html',{"section_list" : section_list})
and in your urls.py add this as one of the urlpatterns
path('section/<int:subject_id>/', views.sections, name='section'),
as for your home.html
<ul>
{% for subject in subject_list %}
<li>
<a href="{% url 'section' subject.id %}">
<img class="thumbnail" src="{{ subject.thumbnail.url }}" alt="">
<span><strong> {{ subject.name }} </strong> </span>
</a>
<p>No of Section : {{ subject.total_section }} </p>
</li>
{% endfor %}
</ul>
and your sections.html
<ul>
{% for section in section_list %}
<li> {{ section.title }} </li>
{$ endfor %}
</ul>
Answer fully edited to take into account the modifications you made in your requirements.
1. The model:
Please add a related name to the foreign key to improve readability:
class Section(models.Model):
subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='sections')
2. The subject page :
Where you can show all the sections related to the selected subject.
The view:
You take a second argument to know which subject you should display:
#login_required
def sections(request, subject_id):
try: # First, you get the requested subject (if it exists)
subject = Subject.objects.get(id=subject_id)
except Subject.DoesNotExist: # Use Django shortcuts to display 404 if necessary
raise Http404("There is no subject with this id.")
sections = subject.sections
return render (request, 'sections.html', {'sections': sections})
The template:
You can know access the sections fields by using {{section.field}} in a forloop:
<ul>
{% for section in sections %}
<li class="sub">
<a name='thumb' class="thumb" href="#">
<span><strong> {{ section.title }} </strong> </span>
</a>
<p>Name: {{ section.teacher }} </p>
{{ section.price }}
</li>
{% endfor %}
</ul>
3. The home page :
The view:
The view can stay the same:
#login_required
def home(request):
subject_list = Subject.objects.all()
return render (request, 'home.html', {'subject_list': subject_list })
The template:
You change the url tag by giving the correct url name and the id of the section to display:
<ul>
{% for subject in subject_list %}
<li class="sub">
<a name='thumb' class="thumb" href="{% url 'section' subject.id %}">
<img class="thumbnail" src="{{ subject.thumbnail.url }}" alt="">
<span><strong> {{ subject.name }} </strong> </span>
</a>
<p>No of Section : {{ subject.total_section }} </p>
</li>
{% endfor %}
</ul>
4. The URLs:
You have to add the new argument that we are using for the section:
urlpatterns = [
path('', views.my_login, name='login'),
path('section/<int:subject_id>/', views.sections, name='section'),
]
And this should work.

NoReverseMatch in Django 2

I'm kinda new at this, and I believe I have misunderstood some things so I'll try to describe it as best possible.
I have 3 tables(models), Game, Chapter, Thread.
Chapter and Thread are connected with the Game table.
models.py
class Game(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Chapter(models.Model):
title = models.CharField(max_length=80)
content = models.CharField(max_length=10000, null=True)
game = models.ForeignKey(Game, on_delete=models.CASCADE)
def __str__(self):
return self.chapter
class Thread(models.Model):
title = models.CharField(max_length=100)
content = models.CharField(max_length=1000, null=True)
game = models.ForeignKey(Game, on_delete=models.CASCADE)
def __str__(self):
return self.title
views.py
def chapter(request, game_id):
auth = top_menu = True
chapters = Chapter.objects.filter(game=game_id)
return render(request, 'chapters.html', {"chapters": chapters, "auth": auth, "top_menu": top_menu})
def thread(request, game_id):
auth = top_menu =True
threads = Thread.objects.filter(game=game_id)
return render(request, 'threads.html', {"auth": auth, "threads": threads, "top_menu": top_menu})
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', index, name="index"),
path('signup/', signup, name="signup"),
path('logout/', logout_view, name="logout"),
path('login/', login_view, name="login"),
path('<int:game_id>/chapters/', chapter, name="chapter"),
path('<int:game_id>/threads/', thread, name="thread"),
]
index.html
{% extends 'base.html' %}
{% block content %}
<div class="container">
<div class="wrapper">
<div class="row">
<div class="col-lg-12 text-center" style="margin-bottom:80px;">
<h1>Welcome to Solo Rpg Helper</h1>
</div>
</div>
{% if auth %}
<div class="row">
<div class="col-lg-12 text-center">
<h1>Your games:</h1>
<ul class="list-group list-group-flush">
{% for game in games.all %}
<li class="list-group-item">{{ game.title }}</li>
{% endfor %}
</ul>
</div>
</div>
{% else %}
<div class="row">
<div class="col-lg-12 text-center sign-buttons">
<h3>Sign in Sign up</h3>
</div>
</div>
{% endif %}
</div>
</div>
{% endblock %}
chapter.html
{% extends 'base.html' %}
{% block top_menu %}
<li>Games</li>
<li>Chapters</li>
<li>Threads</li>
{% endblock %}
{% block content %}
<div class="container">
<div class="wrapper">
{% for chapter in chapters.all %}
<div class="row">
<div class="col-lg-6">
<h1>{{ chapter.title }}</h1>
</div>
<div class="col-lg-6">
<p>{{ chapter.content }}</p>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
index.html works fine because I loop the games so I can access game.id.
In the chapter.html I want to use again game.id but I'm not sure how to access it although it is passed in the function chapter in the views.py (I can see it in the terminal).
If I use it like this:
<li>Chapters</li>
it works, but if I use game.id as in index.html:
<li>Chapters</li>
I get the error:
I'm sorry for the long post.
def chapter(request, game_id):
auth = top_menu = True
chapters = Chapter.objects.filter(game=game_id)
return render(request, 'chapters.html', {"chapters": chapters, "auth": auth, "top_menu": top_menu})
You can't use game.id in the chapters.html template at the moment, because the view doesn't include game in the context dictionary.
A typical approach is to use get_object_or_404, to handle the case when no game matches game_id.
from django.shortcuts import get_object_or_404
def chapter(request, game_id):
auth = top_menu = True
game = get_object_or_404(Game, pk=game_id)
chapters = Chapter.objects.filter(game=game_id)
return render(request, 'chapters.html', {"chapters": chapters, "auth": auth, "top_menu": top_menu, "game": game})

How to create a search function on a class-based list view?

I am trying to create a search function based on the title of my posts. Right now I am trying to implement this search using a filter but the list view is not rendering. I am unsure if I should implement a URL for my search function.
This is my model:
class Post(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(default = 'default0.jpg', upload_to='course_image/')
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=6)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
feedback = models.ManyToManyField(Feedback)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk' : self.pk})
This is my class-based list view:
class PostListView(ListView):
model = Post
template_name = 'store/sub_home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['date_posted']
paginate_by = 12
def get_queryset(self):
object_list = super(PostListView, self).get_queryset()
search = self.request.GET.get('q', None)
if search:
object_list = object_list.filter(title__icontains = title)
return object_list
This is my search bar:
<div id="search">
<form method='GET' action=''>
<input type="text" name='q' placeholder="">
<button id='search_holder'>
<img src="/static/store/search_icon.gif" id="search_icon">
</button>
</form>
</div>
This is my html that is rendering the posts:
{% extends "store/base.html" %}
{% block content %}
{% include "store/home_ext.html" %}
<div style="padding-top: 20px;" id="main" >
<section class="text-center mb-4">
<div class="row" id="random">
{% for post in posts %}
{% include "store/card.html" %}
{% endfor %}
</div>
<div class="row" id="subscription" style="display: none;">
{% if not subs %}
<h2>You have not subscribed to any course :/</h2>
{% endif %}
{% for post in subs %}
{% include "store/card.html" %}
{% endfor %}
</div>
<div class="row" id="content" style="display: none;">
{% if not mine %}
<h2>You have not published anything :/</h2>
{% endif %}
{% for post in mine %}
{% include "store/card.html" %}
{% endfor %}
</div>
</section>
{% include "store/pagination.html" %}
</div>
{% endblock content %}
This is my card.html:
{% load extra_filter %}
<div class="col-lg-3 col-md-6 mb-4">
<div id="course_card">
<div class="view overlay">
<img style="margin-left: -10px;" src="{{ post.image.url }}" alt="">
</div>
<div>
<div>
<strong>
{% if user.is_authenticated %}
<a class="title" href="{% url 'post-detail' post.id %}" >
{% else %}
<a class="title" href="{% url 'login' %}" >
{% endif %}
{% if post.title|length < 30 %}
<span>{{ post.title }}</span>
{% else %}
<span>{{ post.title|cut:27 }}</span>
{% endif %}
<span style="background-color: rgb(253, 98, 98);" class="badge badge-pill danger-color">NEW
</span>
</a>
</strong>
</div>
<div class="star-ratings-css">
<div class="star-ratings-css-top" style="width: {{ post.feedback|calc_rating }}%"><span>★</span><span>★</span><span>★</span><span>★</span><span>★</span></div>
<div class="star-ratings-css-bottom"><span>★</span><span>★</span><span>★</span><span>★</span><span>★</span></div>
</div>
<a href="{% url 'user-posts' post.author.username %}" class="author">
by {{ post.author }}
</a>
<div>
<strong style="text-align: right;" class="price">S${{ post.price }}
</strong>
</div>
<small class="date">
{{ post.date_posted|date:'d F y'}}
</small>
</div>
</div>
</div>
As Nalin Dobhal mentioned in comments, context_object_name should be posts not post. Because in template, you are iterating through posts context variable. Also, when using search functionality, the implementation should be like this:
class PostListView(ListView):
model = Post
template_name = 'store/sub_home.html' # /_.html
context_object_name = 'posts'
ordering = ['date_posted']
paginate_by = 12
def get_queryset(self, *args, **kwargs):
object_list = super(PostListView, self).get_queryset(*args, **kwargs)
search = self.request.GET.get('q', None)
if search:
object_list = object_list.filter(title__icontains = search)
return object_list
Because you are sending the search query through URL querystring(ie: url will look like /posts/?q=title in browser). I am using request.GET.get('q') to fetch those query string values, and use it to filter the queryset.

django templates to views does not render to models data

this is my django 1.8 project, however it does not shows the models' data in the admin:
My admin site has some posts but it does not show on the web:
Directory tree:
mysite/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
]
blog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# post views
url(r'^$', views.post_list, name='post_list'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$',
views.post_detail,
name='post_detail'),
]
blog/views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.published.all()
return render(request, 'blog/post/list.html', {'posts': posts})
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
return render(request, 'blog/post/detail.html', {'post': post})
blog/models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager, self).get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
objects = models.Manager() # The default manager.
published = PublishedManager() # The Dahl-specific manager.
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:post_detail',
args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
blog/templates/blog/base.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link href="{% static "css/blog.css" %}" rel="stylesheet">
</head>
<body>
<div id="content">
{% block content %}
{% endblock %}
</div>
<div id="sidebar">
<h2>My blog here</h2>
<p>This is my blog.</p>
</div>
</body>
</html>
blog/templates/blog/post/list.html
{% extends "blog/base.html" %}
{% block title %}My Blog{% endblock %}
{% block content %}
<h1>My Blog up</h1>
{% for post in posts %}
<h2><a href="{{ post.get_absolute_url }}">
{{ post.title }}</a></h2>
<p class="date">Published {{ post.publish }} by {{ post.author }}</p>
{{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
{% endblock %}
blog/templates/blog/post/detail.html
{% extends "blog/base.html" %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
<h1>{{ post.title }}</h1>
<p class="date">Published {{ post.publish }} by {{ post.author }}</p>
{{ post.body|linebreaks }}
{% endblock %}