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 %}
Related
Disquaire\urls.py
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from store import views
urlpatterns = [
url(r'^$', views.index),
url(r'^store/', include('store.urls')),
url(r'^admin/', admin.site.urls),
]
store.urls.py
urlpatterns = [
url(r'^$', views.listing, name='listing'),
url(r'^(?P<album_id>[0-9]+)/$', views.details, name="details"),
url(r'^search/$',views.search,name='search'),
]
list.html
{% for album in albums %}
<div class="col-sm-4 text-center">
<a href="/store/ {% url 'details' album_id=album.id %}">
<img class="img-responsive" src="{{ album.picture }}" alt="{{ album.title }}">
</a>
<h3>{{ album.title }}</h3>
{% for artist in album.artists.all %}
<p>{{ artist.name }}</p>
{% endfor %}
</div>
{% if forloop.counter|divisibleby:3 %}<div class="clearfix"></div>{% endif %}
{% endfor %}
views.py
def details(request, album_id):
album = Albums.objects.get(pk=album_id)
artists = " ".join([artist.name for artist in album.artists.all()])
message = "Le nom de l'album est {}. Il a été écrit par {}".format(album.title, artists)
return HttpResponse(message)
index.html
{% extends 'store\base.html' %}
{% block content %}
{% include 'store\list.html' %}
{% endblock %}
This is the error I get
Page not found
I have already tried many proposals from the site but nothing work, or maybe I didn't applied them well.I am new to Python and Django so I would appreciate all help.
You have written your urls in the manner /store/ {% url 'details' album_id=album.id %} for some reason. The url template tag will give you a relative url from the domain of your site, hence you don't have to prefix your url. Also you write src="{{ album.picture }}" here I assume picture is an image field? If so you should be writing src="{{ album.picture.url }}" instead. Hence change your template to:
{% for album in albums %}
<div class="col-sm-4 text-center">
<a href="{% url 'details' album_id=album.id %}">
<img class="img-responsive" src="{{ album.picture.url }}" alt="{{ album.title }}">
</a>
<h3>{{ album.title }}</h3>
{% for artist in album.artists.all %}
<p>{{ artist.name }}</p>
{% endfor %}
</div>
{% if forloop.counter|divisibleby:3 %}<div class="clearfix"></div>{% endif %}
{% endfor %}
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 %}
I'm trying to make a simple portofolio app using django but I'm keep getting this error.
I looked everywhere on google but nothing helps.
I'm basically trying to link the Read more button(in project_index.html) to the project_details.html page using {% url 'project_detail' pk=project.pk %}
Views.py:
from django.shortcuts import render
from projects.models import Project
# Create your views here.
def project_index(request):
projects = Project.objects.all()
context = {"projects": projects}
return render(request, "project_index.html", context)
def project_detail(request, pk):
project = Project.objects.get(pk=pk)
context = {"project": project}
return render(request, "project_detail.html", context)
Urls.py:
from django.urls import path
from projects import views
urlpatterns = [
path("", views.project_index, name="project_index"),
path("/int:pk/", views.project_detail, name="project_detail"),
]
models.py:
from django.db import models
# Create your models here.
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
image = models.FilePathField(path="/img")
project_index.html:
{% extends "base.html" %}
{% load static %}
{% block page_content %}
<h1>Projects</h1>
<div class="row">
{% for project in projects %}
<div class="col-md-4">
<div class="card mb-2">
<img class="card-img-top" src="{% static project.image %}">
<div class="card-body">
<h5 class="card-title">{{ project.title }}</h5>
<p class="card-text">{{ project.description }}</p>
**<a href="{% url 'project_detail' pk=project.pk %}"**
class="btn btn-primary">Read More</a>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
project_detail.html:
{% extends "base.html" %}
{% load static %}
{% block page_content %}
<h1>{{ project.title }}</h1>
<div class="row">
<div class="col-md-8">
<img src="{% static project.image %}" alt="" width="100%">
</div>
<div class="col-md-4">
<h5>About the project:</h5>
<p>{{ project.description }}</p>
<br>
<h5>Technology used:</h5>
<p>{{ project.technology }}</p>
</div>
</div>
{% endblock %}
Thanks in advance.
correct your url
path("<int:pk>/", views.project_detail, name="project_detail")
I want to iterate over my postlist, to show on click all the posts with the same tag.
I want them to display at the index.html .
I understand the function, but i don´t know how to implement it into my template.
My views.py
from django.views import generic
from .models import Post
from django.shortcuts import render
class PostList(generic.ListView):
model = Post
template_name = 'index.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
def tag(request, slug):
posts = Post.objects.filter(tags__slug=tag)
return render(request, 'index.html', {"post_list": posts, "tag": tag})
def about(request):
return render(request, 'about.html', {})
My template
<header class="masthead" >
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="site-heading">
<h5 class=" site-heading mt-3"> Erfolgreiche Problemlösungen in der Programmierung, Linux und Windows</h5>
<p class="texthead">
</p>
</div>
</div>
</div>
</div>
</div>
</header>
<div class="container">
<div class="row">
<!-- Blog Entries Column -->
<div class="col-md-8 mt-3 left">
{% for post in post_list %}
<div class="card mb-4" >
<div class="card-body">
<h2 class="card-title">{{ post.title }}</h2>
<p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on | date:"d M Y"}} | Tag:
{% for tag in post.tags.all %}
<a class="mycardtext" href="{% url 'tag' tag.slug %}">{{ tag.name }}</a>
{% empty %}
None
{% endfor %}
</p>
<p class="card-text">{{post.content|truncatewords:25|safe}}</p>
<div><a href="{% url 'post_detail' post.slug %}"
class="btn btn-danger">Weiterlesen</a></h3>
</div>
</div>
</div>
{% endfor %}
</div>
{% block sidebar %}
{% include 'sidebar.html' %}
{% endblock sidebar %}
</div>
</div>
{%endblock%}
My Urls.py
from . import views
from django.urls import path
from django.urls import include
from django.views.generic.base import RedirectView
favicon_view = RedirectView.as_view(url='/home/UrosDobricic/mysite/static/favicon.png', permanent=True)
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('about', views.about, name='about'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
path("tag/<slug:slug>/", views.tag, name='tag'),
]
The tags are shown on the blog. My problem is, that i created in the views.py this post_list = Post.objects.filter(tags__slug=tag), but in my template i have no posts definded.
So when i define the part :{% for tag in post.tags.all %} into to {% for tag in post_list.tags.all %}, it shows me "NONE" at my blog.
I can´t get the right solution, so i wanted to ask if somebody has a tip for me.
Generally this means that i have to display
{% for tags in post_list %}
{{ tags }}
{% endfor %}
Or am I wrong?
If somebody can answer with an example based on my files, that would be great.
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 %}