how to make a list of posts titles in django - python

I am creating a blog web app with django where i want to make a list which contains only titles of the posts.
i wanna make two lists namely
Latest posts
All posts
In Latest posts , i wanna list out titles of the posts created recently.Means post created at last should be in first place of the list. simple
In All Posts , i want to list out titles of all posts in ascending order.
i am not sure how to do it.
Here is my code goes.....
views.py
from django.shortcuts import render , redirect
from django.views.generic import TemplateView , ListView , DetailView
from .models import home_blog_model
from .forms import create_post
class home_view(ListView):
model = home_blog_model
template_name = "home.html"
context_object_name = "posts"
def detail_view(request , pk):
obj = home_blog_model.objects.get(id=pk)
context = {"obj":obj}
return render(request , "detail.html" , context)
def create_post_view(request):
if request.method == "POST":
form = create_post(request.POST)
if form.is_valid():
form.save()
return redirect("/home/")
else:
form = create_post()
return render(request , "create_post.html" , {"form":form})
home.html
{% extends "base.html" %}
{% load static %}
{% block body %}
<img src="{% static 'hori.jpg' %}" style="margin-top: 50px;margin-left: 250px;width: 60%">
<div class="row" style="margin-top: 40px;margin-left: 320px;margin-right: 20px">
{% for post in posts %}
<div class="col-sm-6 mb-4">
<div class="container" style="width: 300px;box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);transition: 0.3s;width: 100%;padding: 0px;">
<div class="card" style="height: 200px;padding: 12px;" onclick="location.href='{% url 'detail' post.id %}'">
<h2>{{ post.title }}</h2>
<div class="card-body">{{ post.summary }}</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
{% block head %}
<style>
.card:hover { box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);}
</style>
{% endblock %}
models.py
from django.db import models
class home_blog_model(models.Model):
title = models.CharField(max_length=100)
summary = models.CharField(max_length=300)
content = models.TextField()
date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
urls.py
from django.urls import path
from . import views
from django.contrib.auth.views import LoginView , LogoutView
urlpatterns = [
path("" , views.home_view.as_view() , name="blog-home"),
path("posts/<int:pk>/" , views.detail_view , name="detail"),
path("admin/login/" , LoginView.as_view(template_name="admin-login.html") , name="admin-login"),
path("admin/logout/" , LogoutView.as_view() , name="admin-logout"),
path("admin/post/create/" , views.create_post_view , name="create_post"),
]
thanks in advance.

You can use dictsortreversed for latest posts. For example:
# top 5 posts
{% for post in posts|dictsortreversed:"id"|slice:"5" %}
{{ post.title }}
{% endfor %}
In this way you can have posts in ascending order (like the implementation of your code) and reversed order in same template without adding anything in view. slice was added for slicing the list for 5 objects.

Related

How can I get my html to display my django model?

I'm trying to get my django model to be shown in the footer of my base.html but I can't get it to show up. I've looked at a few videos and I can't figure out where I'm going wrong. I know that the model works as I've made 4 entries in my database and I can view them on the admin page. The code also doesn't show any errors so I have nothing to go off of there. Here it is:
Models.py
class SocialMediaPlatform(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
font_awesome_class = models.CharField(max_length=50, blank=True, null=True)
base_url = models.CharField(max_length=50, blank=True, null=True,
default='https://instagram.com/ or https://tiktok.com/#')
def __str__(self):
return self.base_url
Views.py
def social_media_base_view(request):
context = {}
smbase = SocialMediaPlatform.objects.all()
context['smbase'] = smbase
return render(request, 'base.html', context)
Urls.py
urlpatterns = [
path('', views.social_media_base_view),
]
Admin.py
#admin.register(SocialMediaPlatform)
class SocialPlatformAdmin(admin.ModelAdmin):
list_display = ('name', 'font_awesome_class', 'base_url')
base.html
{% for smlink in smbase %}
<a href="{{ smlink.name }}">
<i class="{{ smlink.font_awesome_class }}">
</a>
{% endfor %}
Look what you are passing as context:
def social_media_base_view(request):
...
smbase = SocialMediaPlatform.objects.all()
context['smbase'] = smbase
return ...
It's QuerySet of SocialMediaPlatform objects. It means, that you can render them one by one with for loop:
{% for smlink in smbase %}
{{ smlink.name }}
{% endfor %}
You don't need to call SocialMediaPlatform model additionaly.
in your view you use:
return render(request, 'index.html', context)
i can not see, if you are defined index.html
Somethere in index you should have
{% extends base.htm %}
The second, i am agree with #Shabble:
{% for smlink in smbase %}
<a href="{{ smlink.name }}">
<i class="{{ smlink.font_awesome_class }}">
</a>
{% endfor %}
The last:
Try to use Django-GCBV TemplateView. Or ListView, in your case it is better:
somethere in views.py
Class MyListView(ListView):
model = SocialMediaPlatform
template_name = index.html
somethere in urls.py
urlpatterns = [
path('', MyListView.as_view()),
]
somethere in index.html
{% for smlink in object_list %}
<a href="{{ smlink.name }}">
<i class="{{ smlink.font_awesome_class }}">
</a>
{% endfor %}

Getting no reverse match at /post in django

I have been facing this issue. And I have a url name post-page-detail but then also getting error please
See the error screenshot below.
My html page
<a href="{% url "post-detail-page" slug=post.slug %}">
<h2>{{post.tractor_company}} || {{post.tractor_model}}</h2>
<pre><h5>{{post.implimentaion}}</h5>
{{post.farmer}}
Uplode Date : {{post.date}}</pre>
</a>
</div>
URLs.py
from . import views
urlpatterns = [
path("",views.starting_page,name = "starting-page"),
path("posts",views.posts,name = "post-page"),
path("posts/<slug:slug>",views.post_detail,name="post-detail-page"),
]
View.py
from django import forms
from django.contrib.auth.models import User
from django.shortcuts import render, redirect ,get_object_or_404
from .models import Post, Farmer
# Create your views here.
from django.http import HttpResponseRedirect
# Create your views here.
def starting_page(request):
return render(request,"tractor/index.html")
def posts(request):
qs = Post.objects.all()
context = {"posts":qs}
return render(request,"tractor/all-post.html",context)
def add_post(request):
pass
def post_detail(request,slug):
indentified_post = get_object_or_404(Post,slug=slug)
return render(request,"blog/post-detail.html",{'post':indentified_post})
i am iterating through posts and using the post-detail.html page
all-post.html.
{% load static %}
{% block title %}
All Tractors
{% endblock %}
{% block content%}
<section id="all_events">
<br>
<h1 style="text-align:center;">All Tractors</h1>
<ul>
{% for post in posts %}
<br>
{% include "tractor/includes/singlePost.html" %}
{% endfor %}
</ul>
</section>
{% endblock %}```
Try this:
{% url 'post-detail-page' post.slug as post_detail_url %}
<a href="{{ post_detail_url }}">
Let me know if it worked.

Managing to use data from one Django application in another but the urls are different

In this previous question I asked about using data from one Django application in another. I wanted to use blog data from my blog application in my pages application. The goal being that my site homepage would show the 3 most recent entries.
The answer provided was acceptable at the time. However, I've since wanted to now set the blog items that appear on my homepage to act as links to the blog item itself but the blog items on my homepage have a different url path. Is there any way around this?
Here is my code:
Blog
from .views import (
BlogListView,
BlogUpdateView,
BlogDetailView,
BlogDeleteView,
BlogCreateView,
)
urlpatterns = [
path('<int:pk>/edit/',
BlogUpdateView.as_view(), name='Blog_edit'),
path('<int:pk>/',
BlogDetailView.as_view(), name='Blog_detail'),
path('<int:pk>/delete/',
BlogDeleteView.as_view(), name='Blog_delete'),
path('new/', BlogCreateView.as_view(), name='Blog_new'),
path('', BlogListView.as_view(), name='Blog_list'),
]
models.py
class Blog(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
thumb = models.ImageField(blank=True, null=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('Blog_detail', args=[str(self.id)])
views.py
class BlogListView(ListView):
model = Blog
template_name = 'blog_list.html'
class BlogDetailView(DetailView):
model = Blog
template_name = 'blog_detail.html'
login_url = 'login'
class BlogUpdateView(LoginRequiredMixin, UpdateView):
model = Blog
fields = ('title', 'body', 'thumb')
template_name = 'blog_edit.html'
login_url = 'login'
def test_func(self):
obj = self.get_object()
return obj.author == self.request.user
class BlogDeleteView(LoginRequiredMixin, DeleteView):
model = Blog
template_name = 'blog_delete.html'
success_url = reverse_lazy('blog_list')
login_url = 'login'
def test_func(self):
obj = self.get_object()
return obj.author == self.request.user
class BlogCreateView(LoginRequiredMixin, CreateView):
model = Blog
template_name = 'blog_new.html'
fields = ('title', 'body', 'thumb')
login_url = 'login'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
pages
urls.py
urlpatterns = [
path('', HomePageView, name='home'),
]
views.py
def HomePageView(request):
context = {}
blog = Blog.objects.order_by('-date')[:3]
context['blog']=blog
return render(request,'home.html',context)
home.html
{% extends 'base.html' %}
{% block title %}Home{% endblock title %}
{% block content %}
<div class="jumbotron">
<h1 class="display-4">Lakeland Cycle Club</h1>
<p class="lead">The home of cycling in Fermanagh.</p>
<p class="lead">
<a class="btn btn-primary btn-lg" href="{% url 'blog_list' %}" role="button">View All Club News</a>
</p>
{% for new in blog%}
<div class="card" style="width: 300px; display: inline-block; margin: 5px; vertical-align: top;">
<div class="card-header">
<span class="font-weight-bold">
{{ new.title }}
</span> ·
<span class="text-muted">by {{ new.author }} | {{ new.date }}</span>
</div>
<div class="card-body">
{% if blog.thumb %}
<p align="center"><img src="{{ new.thumb.url }}" /></p>
{% endif %}
<p>{{ new.body | linebreaks | truncatewords:30 }}
</div>
</div>
{% endfor %}
{% endblock content %}
More info.
I think if I add a URL to my title({{ new.title }}) it might work as I want. I tried {{ new.title }} but got this error:
django.urls.exceptions.NoReverseMatch: Reverse for 'blog_detail' with no arguments not found. 1 pattern(s) tried: ['blog/(?P<pk>[0-9]+)/$']
The reason is most likely because each item in my home page has no way of identifying the primary key for the specific blog entry. If I change the url to blog_list no primary key is required so I'm taken to the blog_lost page without any issue. How can I add a URL link and ensure it links to the correct blog_detail post?
I made the following changes:
templates/home.html
I changed
<span class="font-weight-bold">
{{ new.title }}
</span> ·
for
<span class="font-weight-bold">
{{ new.title }}
</span> ·
pages/urls.py
I added
from blog.views import BlogDetailView
and changed
urlpatterns = [
path('', HomePageView, name='home'),
]
to
urlpatterns = [
path('blog/<int:pk>/',
BlogDetailView.as_view(), name='pages_blog_detail'),
path('', HomePageView, name='home'),
]

Associate multiple unique forms to a unique object in Django

I'm trying to build a web application using Django where a user can create a 'Project' and within that 'Project', there are four different forms.
My Question is, how do I associate those forms to a specific 'project' in the sense that the form is linked to that specific 'project'.
I'm close to doing it but I'm having issues with the 'create-project.html', 'create-request-1.html' and 'create-request-2.html' pages from rendering due to the 'PK' in the 'projects.html' page URL.
The exact errors I get for navigating to those pages is -
NoReverseMatch at /projects/create-project/
Reverse for 'initiate_project' with no arguments not found. 1 pattern(s) tried: ['projects\\/project\\/(?P<pk>[0-9]+)\\/$']
Or
NoReverseMatch at /project/create-post-1/
Reverse for 'initiate_project' with no arguments not found. 1 pattern(s) tried: ['projects\\/project\\/(?P<pk>[0-9]+)\\/$']
The path is as follows -
'projects.html' -
'create-project.html' -
'initiate-project.html' -
'create-request-1.html'
'create-request-2.html'
I can navigate and go into each unique 'project' (e.g. project 1, project 2) in 'projects.html' but I can't get into my forms ('create-request-1.html', 'create-request-2.html') inside the 'initiate-project.html' page that's within each 'project' in the 'projects.html' page.
Here's my code so far -
model.py -
from django.db import models
class create_new_project(models.Model):
list_display = ('project_name', 'project_manager',
'technical_lead', 'test_lead')
class Meta:
verbose_name = 'Create New Project'
verbose_name_plural = 'Create New Projects'
project_name = models.CharField(max_length=100)
project_manager = models.CharField(max_length=100)
technical_lead = models.CharField(max_length=100)
test_lead = models.CharField(max_length=100)
environment_choices = (
('1', '1'),
('2', '2'),
('3', '3')
)
environment = models.CharField(
max_length=50, choices=environment_choices, default='ICCS')
def __str__(self):
return self.project_name
views.py
from django.shortcuts import render
from django.shortcuts import render, get_object_or_404
from main.models import *
# Create your views here.
def index(request):
return render(request, 'main/index.html')
def projects(request):
CreateNewProject = create_new_project.objects.all()
args = {'CreateNewProject': CreateNewProject}
return render(request, 'main/projects.html', args)
def create_project(request):
return render(request, 'main/create-project.html')
def initiate_project(request, pk):
InitiateProjectURL = get_object_or_404(create_new_project, pk=pk)
return render(request, 'main/initiate-project.html', {'InitiateProjectURL': InitiateProjectURL})
def create_post_request_1(request):
return render(request, 'main/create-post-request-1.html')
def create_post_section_2(request):
return render(request, 'main/create-post-request-2.html')
urls.py
from django.urls import include, path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('projects/', views.projects, name='projects'),
path('projects/create-project/', views.create_project, name='create_project'),
path('projects/project/<int:pk>/',
views.initiate_project, name='initiate_project'),
path('project/create-post-request-1/',
views.create_post_request_1, name='create_post_paid_request_section_1'),
path('project/create-post-request-2/',
views.create_post_request_2, name='create_post_request_2'),
]
projects.html
<div class="row">
<a href="{% url 'create_project' %}" class="card card-1 bg-red shadow m-2">
<div class="card-body d-flex h-100">
<div class="text-center mx-auto justify-content-center align-self-center">
{% load staticfiles %}
<img src="{% static 'main/images/plus.svg' %}" alt="Plus Icon" height="60vh">
<div class="mb-3 pt-4 text-white">Create New Project</div>
</div>
</div>
</a>
{% for create_new_project in CreateNewProject %}
<div class="card card-1 bg-white shadow m-2">
<div class="card-body">
<h4 class="card-title text-red">{{ create_new_project.project_name }}</h4>
<div class="card-text pt-2 pb-2">
<div class="mb-3"><b>Project Manager: </b>{{ create_new_project.project_name }}</div>
<div class="mb-3"><b>Project Lead: </b>{{ create_new_project.project_manager }}</div>
<div class="mb-3"><b>Test Lead: </b>{{ create_new_project.test_lead }}</div>
<div class="mb-3"><b>Environment: </b>{{ create_new_project.environment }}</div>
</div>
<div class="float-right">
<a href="{% url 'initiate_project' pk=create_new_project.pk %}" class="text-red">
{% load staticfiles %}
<img src="{% static 'main/images/next.svg' %}" class="text-red" alt="Next Icon" height="25vh"></a>
</div>
</div>
</div>
{% endfor %}
</div>
create-post-request-1.html / create-post-request-2.html
<div class="col-md-2">
Cancel
</div>
To better illustrate what I'm trying to do, See the following image - Visual description
the href for the a tag in create-post-request-1.html / create-post-request-2.html should be sth like "{% url 'initiate_project' pk=any_pk_you_choose %}" instead of {% url 'initiate_project' %}

Django objects.all() doesn`t display any content

Hi everybody!
Im just starting a way of django programming so sometimes really get confused.
I`m trying to display all my objects from DB, but when opening the page its simply empty.
There are content added and I tried ListView previously and it worked for me. But now I need to dislpay objects like a grid and here is an issue with this method.
Will be very thanksfull for any help!
models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=140)
body = models.TextField()
date = models.DateField()
image = models.ImageField(upload_to='bons_images/%Y/%m/%d')
def __str__(self):
return self.title
views.py
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django.views import generic
from blog.models import Post
def image(request):
post = Post()
variables = RequestContext(request, {
'post': post
})
return render_to_response('blog/post.html', variables)
# class IndexView(generic.ListView):
# template_name = 'blog/blog.html'
# context_object_name = 'all_posts'
#
# def get_queryset(self):
# return Post.objects.all()
def index(request):
posts = Post.objects.all()
return render(request, 'blog/blog.html', {'posts': posts})
urls.py
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post
from blog import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<pk>\d+)$', DetailView.as_view(model=Post, template_name='blog/post.html')),
]
blog.html
{% extends 'base.html' %}
{% block content %}
{% if all_posts %}
{% for post in all_posts %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-lg-4">
<div class="thumbnail">
<a href="/blog/{{ post.id }}">
<h5>{{ post.date|date:'Y-m-d' }} {{ post.title }}</h5>
<img src="{{ post.image.url }}" style="width: 50%; height: 50%"/>
</a>
</div>
</div>
</div>
</div>
{% endfor %}
{% endif %}
{% endblock %}
And by the way, how its possible to display your objects like in grid, not list, using Bootstrap or so on.
Thank you!
You're iterating over something called all_posts in your template. But your view doesn't send anything called all_posts; it only sends posts. You need to use consistent names.

Categories