Django dynamic homepage - python

I have a lots of apps, but I want to generate all app's data on my homepage. Here's my apps:blog,members
I want to show blogs and my members on my homepage
I know that if I want to generate one app's data,I can do this:
blog/urls.py:
urlpatterns = [
url(r'^$', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:10],
template_name='blog1.html')),
and in blog1.html:
{% extends "index.html" %}
{% block blog %}
{% for post in blog_post %}
<div id="blog-wrapper" class="bgrid-third s-bgrid-half mob-bgrid-whole group">
<article class="bgrid">
<h5>{{ post.date }} </h5>
<h3><div class = "entry-title">{{ post.title }}</div></h3>
<p>{{ post.user }}</p>
<p><div class = "post_body">{{ post.body|safe|linebreaks }}</div></p>
</article>
</div>
{% endfor %}
{% endblock %}
{% block member %}
Here when I go to the url,I can see all blogs I write,but now I want to see blogs and members(another app) on one page, so how can I do this?

I would suggest you to use ListView's get_context_data method.
Create view in your project's views.py:
from django.views.generic import ListView
# Import your models here.
class HomepageView(ListView):
model = Post
ordering = '-date'
template_name = 'blog1.html'
context_object_name = 'posts'
def get_context_data(self, **kwargs):
context = super(HomepageView, self).get_context_data(**kwargs)
context['members'] = Member.objects.all()
return context
def get_queryset(self):
return super(HomepageView, self).get_queryset()[:10]
Then, change urls.py:
from django.conf.urls import url
# Import ``HomepageView`` here.
urlpatterns = [
url(r'^$', HomepageView.as_view(), name='homepage'),
# Other patterns here.
]
Now you can access posts using posts variable and members using members variable.

from .models import Post
from member.models import UserProfile
def get_data():
return {
"post": Post.objects.all().order_by("-date")[:10],
"user": UserProfile.objects.all()[:10]
}
then in my blog1.html:
{% extends "index.html" %}
{% block blog %}
{% for post in object_list.post %}
<div id="blog-wrapper" class="bgrid-third s-bgrid-half mob-bgrid-whole group">
<article class="bgrid">
<h5>{{ post.date }} </h5>
<h3><div class = "entry-title">{{ post.title }}</div></h3>
<p>{{ post.user }}</p>
<p><div class = "post_body">{{ post.body|safe|linebreaks }}</div></p>
</article>
</div>
{% endfor %}
{% endblock %}
{% block member %}
{% for post in object_list.user %}
<div class="bgrid member">
<div class="member-header">
<div class="member-pic">
<img src="{{ post.portrait }}" alt=""/>
</div>
<div class="member-name">
<h3>{{ post.user }}</h3>
<span>Creative Director</span>
</div>
</div>
<p>{{ post.intro }}</p>
<ul class="member-social">
<li><i class="fa fa-google-plus"></i></li>
<li><i class="fa fa-github"></i></li>
</ul>
</div> <!-- /member -->
{% endfor %}
{% endblock %}

Related

ProgrammingError at /blog/ django project in ubuntu vps

I encountered this error after deploying the project on a Linux server. But when running it on localhost, I had no error like this in addition that I say, I have a blog application
views.py
from django.views import generic
from .models import Post
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by("-created_at")
template_name = "blog/blog.html"
class PostDetail(generic.DetailView):
model = Post
template_name = "blog/blogContent.html"
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.PostList.as_view(), name="blog"),
path("<slug:slug>/", views.PostDetail.as_view(), name="post_detail"),
]
blog.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<main class="main">
<div class="container blog_container">
<h2>وبلاگ</h2>
<div class="content_container">
{% for post in post_list %}
<div class="content">
<img src="{{ post.image.url }}" alt="" >
{{ post.title }}
<p>{{ post.author }} </p>
<p>{{ post.created_at|timesince }}</p>
<br>
<p class="description">{{post.content|slice:":200" }} </p>
</div>
{% endfor %}
</div>
</div>
</main>
<!-- START FOOTER COMPONENT -->
{% endblock content %}

Comments in the admin panel are added, but they are not visible on the site

Based on this tutorial https://www.youtube.com/watch?v=An4hW4TjKhE&ab_channel=AbhishekVerma
I'm trying to add the ability to add comments under posts, add a comment in the admin panel, everything is ok, but the site does not display anything under the post
here is models.py
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
class Post(models.Model):
published = None
title = models.CharField(max_length=200)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = models.TextField()
header_image = models.ImageField(blank=True, null=True, upload_to="images/", default='fox.jpeg')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail', args=[str(self.id)])
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_post')
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_user')
content = models.TextField(max_length=160)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '{}-{}'.format(self.post.title, str(self.user.username))
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from .models import Post, Comment
from django import forms
from .forms import *
class BlogListView(ListView):
model = Post
template_name = 'home.html'
context_object_name = 'posts'
paginate_by = 2
queryset = Post.objects.all()
class BlogDetailView(DetailView):
model = Post
template_name = 'post_detail.html'
class BlogCreateView(CreateView):
model = Post
template_name = 'post_new.html'
fields = ['title', 'author', 'body', 'header_image']
class BlogUpdateView(UpdateView):
model = Post
template_name = 'post_edit.html'
fields = ['title', 'body', 'header_image']
class BlogDeleteView(DeleteView):
model = Post
template_name = 'post_delete.html'
success_url = reverse_lazy('home')
#property
def image_url(self):
"""
Return self.photo.url if self.photo is not None,
'url' exist and has a value, else, return None.
"""
if self.image:
return getattr(self.photo, 'url', None)
return None
def post_detail(request, id, slug):
post = get_object_or_404(Post, id=id, slug=slug)
comments = Comment.objects.filter(post=post).order_by('-id')
is_liked = False
if post.likes.filter(id=request.user.id).exists():
is_liked = True
if request.method == 'POST':
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
content = request.POST.get('content')
comment = Comment.objects.create(post=post, user=request.user, content=content)
comment.save()
return HttpResponseRedirect(post.get_absolute_url())
else:
comment_form = CommentForm()
context = {
'post': post,
'is_liked': is_liked,
'total_likes': post.total_likes(),
'comments': comments,
'comment_form': comment_form,
}
return render(request, 'myblog/post_detail.html', context) #his "blog" = my "myblog"
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('content',)
post_detail.html
{% extends 'base.html' %}
{% block content %}
<div class="post-entry">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
<p>+ Edit Blog Post</p>
<p>+ Delete Blog Post</p>
<img src="{{ post.header_image.url|default_if_none:'fox.jpeg' }}">
{{ post.body|urlize }}
{% for comm in post.commentpost_set.all%}
{{ comm.user }} <br>
{{ comm.text }} <br><br>
{% endfor %}
{% endblock content %}
<br><br>
<hr>
<form method="post">
{% csrf_token %}
{{ comment_form.as_p }}
{% if request.user.is_authenticated %}
<input type="submit" value="Submit" class="btn btn-outline-success">
{% else %}
<input type="submit" value="Submit" class="btn btn-outline-success" disabled>
{% endif %}
</form>
<div class="main-comment-section">
{{ comments.count }} Comment{{ comments|pluralize }}
{% for comment in comments %}
<blockquote class="blockquote">
<p class="mb-0">{{ comment.content }}</p>
<footer class="blockquote-footer">by <cite title="Source Title">{{ comment.user|capfirst }}</cite></footer>
</blockquote>
{% endfor %}
</div>
myblog/urls.py
from django.urls import path
from .views import (
BlogListView,
BlogDetailView,
BlogCreateView,
BlogUpdateView,
BlogDeleteView,
)
urlpatterns = [
path('post/new/', BlogCreateView.as_view(), name='post_new'),
path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'),
path('post/<int:pk>/edit/',BlogUpdateView.as_view(), name='post_edit'),
path('post/<int:pk>/delete/',BlogDeleteView.as_view(), name='post_delete'),
path('', BlogListView.as_view(), name='home'),
]
base.html
{% load static %}
<html>
<head>
<title>Django blog</title>
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400"
rel="stylesheet">
<link href="{% static 'css/base.css' %}" rel="stylesheet">
</head>
<body>
<div>
<header>
<div class="nav-left">
<h1>Django blog</h1>
<h2>Admin</h2>
</div>
<div class="nav-right">
+ New Blog Post
</div>
</header>
{% if user.is_authenticated %}
<p>Hi {{ user.username }}!</p>
{% else %}
<p>You are not logged in.</p>
Log In<br>
<p>Sign up</p>
{% endif %}
{% block content %}
{% endblock content %}
</div>
</body>
</html>
<ul class="pagination">
{% if page_obj.has_previous %}
{% if page_obj.number|add:'-3' > 1 %}
<li class="pagination__item">
1
</li>
{% endif %}
{% if page_obj.number|add:'-3' >= 3 %}
<li class="pagination__item pagination__item--dots">
<a href="?{{ genre }}{{ year }}page={{ page_obj.previous_page_number|add:'-3' }}">
<span class="pagination__link">• • •</span>
</a>
</li>
{% endif %}
{% endif %}
{% if paginator.page_range|length > 1 %}
{% for i in paginator.page_range %}
{% if page_obj.number == i %}
<li class="pagination__item active">
<a class="pagination__link" href="#">{{ i }}</a>
</li>
{% elif i > page_obj.number|add:'-4' and i < page_obj.number|add:'4' %}
<li class="pagination__item">
<a class="pagination__link" href="?{{ genre }}{{ year }}page={{ i }}">{{ i }}</a>
</li>
{% endif %}
{% endfor %}
{% endif %}
{% if page_obj.has_next %}
{% if page_obj.number|add:'4' < page_obj.paginator.num_pages %}
<li class="pagination__item pagination__item--dots">
<a href="?{{ genre }}{{ year }}page={{ page_obj.next_page_number|add:'3' }}">
<span class="pagination__link">• • •</span>
</a>
</li>
{% endif %}
{% if page_obj.number|add:'3' < page_obj.paginator.num_pages %}
<li class="pagination__item">
<a class="pagination__link" href="?{{ genre }}{{ year }}page={{ page_obj.paginator.num_pages }}">
{{ page_obj.paginator.num_pages }}
</a>
</li>
{% endif %}
{% endif %}
</ul>
Thanks for any help
Your post_detail.html extends base.html, hence any content you wish to render must be inside some block and this block also must be present in the parent template (base.html here). You currently have some content outside any block and hence they aren't rendered. Put the HTML inside the block and it will show up:
{% extends 'base.html' %}
{% block content %}
<div class="post-entry">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
<p>+ Edit Blog Post</p>
<p>+ Delete Blog Post</p>
<img src="{{ post.header_image.url|default_if_none:'fox.jpeg' }}">
{{ post.body|urlize }}
{% for comm in post.commentpost_set.all%}
{{ comm.user }} <br>
{{ comm.text }} <br><br>
{% endfor %}
<!-- put them inside the block -->
<br><br>
<hr>
<form method="post">
{% csrf_token %}
{{ comment_form.as_p }}
{% if request.user.is_authenticated %}
<input type="submit" value="Submit" class="btn btn-outline-success">
{% else %}
<input type="submit" value="Submit" class="btn btn-outline-success" disabled>
{% endif %}
</form>
<div class="main-comment-section">
{{ comments.count }} Comment{{ comments|pluralize }}
{% for comment in comments %}
<blockquote class="blockquote">
<p class="mb-0">{{ comment.content }}</p>
<footer class="blockquote-footer">by <cite title="Source Title">{{ comment.user|capfirst }}</cite></footer>
</blockquote>
{% endfor %}
</div>
{% endblock content %}

Django - Exclude current post from side bar

I am playing with Django but I'm having trouble with my templates. In my post detail in including a recent posts side bar from a template tag but I want to exclude the current post if it is, in fact, one of the most recent. My original hope was to use .exclude(id__post_detail=post) in the blog_tag but I think I might be missing an important concept, do I need to request post_detail return its response and then I can do that? Or perhaps define the query in the view and then call it to the blog_tag?
Many thanks in advance.
1.blog_tags.py
from django import template
register = template.Library()
from django.db import models
from django.utils import timezone
from ..models import Post
#register.inclusion_tag('blog/sidebar.html')
def sidebar_latest(request, count=5):
latest_posts= Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')[:count]
return {'latest_posts': latest_posts}
views
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
post_detail
{% extends 'blog/base.html' %}
{% load blog_tags %}
{% block content %}
<div class="col-sm-12 col-md-9">
<div class="post">
<h1>{{ post.title }}</h1>
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<p>{{ post.text|linebreaksbr }}</p>
</div>
</div>
<div class="col-sm-12 col-md-3">
{% sidebar_latest 3 %}
</div>
{% endblock %}

I do not understand this Django error

Error during template rendering
In template
C:\Users\Paddy\Desktop\Django-tut\mysite\blog\templates\blog\post_list.html,
error at line 10 Reverse for 'post_detail' with arguments '()' and
keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried:
['blog/post/(?P[0-9]+)/$']
{% extends 'blog/base.html' %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<h1>{{ post.title }}</h1>
<!--<h1>{{ post.title }}</h1>-->
<p>{{ post.text|linebreaks }}</p>
</div>
{% endblock %}
My post_detail.html file looks like this
{% extends 'blog/base.html' %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaks }}</p>
</div>
{% endblock %}
My urls.py is
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
]
and views.py is
from django.shortcuts import render
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
#Post.objects.get(pk=pk)
# Create your views here.
def post_list(request):
return render(request, 'blog/post_list.html', {})
Thanks.
Assuming the first template you've posted is post_list.html you don't send any context variables to it.
In post_list view - if you want to list all posts - you have to add:
def post_list(request):
posts = Post.objects.all()
return render(request, 'blog/post_list.html', {'posts': posts})
Then in your post_list.html template you have to loop over posts:
{% extends 'blog/base.html' %}
{% block content %}
{% for post in posts %} # iterate over posts
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaks }}</p>
</div>
{% endfor %}
{% endblock %}
There error message complains that it can't find a reverse URL when pk is '', the empty string.
Indeed there is no URL that matches that, as the regular expression required [0-9]+, and the empty string doesn't match that. So a reverse match can't be found.
The reason why pk was empty is explained in the other answer.

How can I make two models appear on my Django homepage simultaneously?

I can't make my homepage show data from both my HomePage and IconBlurb models. I've been stucked on this problem for two days and couldn't figure it our. Please help me. Thanks.
This is my models.py
class HomePage(models.Model):
heading = models.CharField(max_length=200,
help_text="The heading under the icon blurbs")
subheading = models.CharField(max_length=200,
help_text="The subheading just below the heading")
introduction = models.TextField(help_text="首页的欢迎文字。")
introLink = models.URLField(max_length=200, blank=True)
class Meta:
verbose_name= _("Home page")
verbose_name_plural = _("Home pages")
This is my views.py
from django.shortcuts import get_object_or_404, render
from homepage.models import HomePage, IconBlurb
def index(request):
homepage = get_object_or_404(HomePage)
return render(request, 'homepage/index.html', {'homepage':homepage})
def blurb(request):
latest_iconblurb = IconBlurb.objects.all()
context = {'latest_iconblurb': latest_iconblurb}
return render(request, 'homepage/blurb.html', context)
This is my urls.py
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
)
This is my index.html
{% extends "base.html" %}
{% block all_content %}
<div class="jumbotron">
<div class="container">
<h1>{{ homepage.heading }}</h1>
<p>{{ homepage.introduction }}</p>
<p><a class="btn btn-primary" href="/courses">开始学习</a></p>
</div>
</div>
<div class="container">
<div class="row">
{% block blurb %}{% endblock %}
</div>
</div>
{% endblock %}
This is my blurb.html
{% extends "homepage/index.html" %}
{% block blurb %}
{% if latest_iconblurb %}
{% for blurb in latest_iconblurb %}
<div class="col-md-4">
<h2>{{ blurb.title }}</h2>
<p>{{ blurb.content }}</p>
</div>
{% endfor %}
{% endif %}
{% endblock %}
This is simple. Write both function code in a single function.
def index(request):
homepage = get_object_or_404(HomePage)
latest_iconblurb = IconBlurb.objects.all()
context = {'latest_iconblurb': latest_iconblurb; 'homepage':homepage}
return render(request, 'homepage/blurb.html', context)

Categories