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

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)

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 %}

How to use django-summernote in templates

I have setup django-summernote on my project and everything is great, it works very good on admin , but i want to use it on my templates.
Note :
in django-summernote documentation they only explain how to use it if you have forms.py file but I dont
my main urls.py :
urlpatterns = [
path('games/', include('core.urls', namespace='core')),
path('summernote/', include('django_summernote.urls')),
]
my app(name=core) urls.py :
from django.urls import path
from . import views
app_name = 'core'
urlpatterns = [
path('new/', views.GameCreate.as_view(), name='game_new'),
path('<int:pk>/edit/', views.GameUpdate.as_view(), name='game_edit'),
]
my views.py :
class GameCreate(LoginRequiredMixin, CreateView):
model = Game
template_name = 'core/game_new.html'
fields = '__all__'
redirect_field_name = 'home'
class GameUpdate(LoginRequiredMixin, UpdateView):
model = Game
template_name = 'core/game_edit.html'
fields = '__all__'
my template file "game_new.html" :
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %} Add New Game {% endblock %}
{% block main %}
<section class="main-section">
<div class="container">
<h1>New Game</h1>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
<input type='submit' value="Save" />
</form>
</div>
</section>
{% endblock %}
my template file "game_edit.html":
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %} Game Info {% endblock %}
{% block main %}
<section class="main-section"></section>
<div class="container">
<h1>Edit Game Info</h1>
<form action="" method="post">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="Update" />
</form>
</div>
</section>
{% endblock %}
my Models.py :
from django.db import models
from django.urls import reverse
# Create your models here.
class Game(models.Model):
name = models.CharField(max_length=140)
developer = models.CharField(max_length=140)
game_trailer = models.CharField(max_length=300, default="No Trailer")
game_story = models.TextField(default='No Story')
Firstly in your template dont forgate to add this:
{{ form.media }} <<<------ To load all js and css attached
In the document your models you must herit summernote widget. Example:
from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
class FormFromSomeModel(forms.ModelForm):
class Meta:
model = SomeModel
widgets = {
'foo': SummernoteWidget(),
'bar': SummernoteInplaceWidget(),
}

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.

Django dynamic homepage

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 %}

Categories