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.
Related
Reverse for 'redirection' with arguments '('',)' not found. 1 pattern(s) tried['Raccourcisseur/Lien/(?P[^/]+)/$']
[About errors][1]
#urls.py#
from django.urls import path
from . import views
urlpatterns = [
path('', views.liste,name='liste'),
path('nouveau/',views.afficher,name='afficher'),
path('Lien/<str:code>/',views.redirection,name='redirection'),
]
#urls.py(global)#
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('Raccourcisseur/',include('mini_url.urls')),
]
#views.py#
from django.shortcuts import render,redirect,get_object_or_404
from .models import MiniURL
from .forms import MiniURLForm
def afficher(request):
if request.method == "POST":
form = MiniURLForm(request.POST)
if form.is_valid():
form.save()
return redirect(liste)
else:
form = MiniURLForm()
return render(request,'mini_url/index.html',{'form':form})
def liste(request):
minis = MiniURL.objects.order_by('-acces')
return render(request, 'mini_url/liste.html', locals())
def redirection(request,code):
""" Redirection vers l'URL enregistrée """
mini = get_object_or_404(MiniURL, code=code)
mini.acces += 1
mini.save()
return redirect(mini.url, permanent=True)
#index.html#
{% extends 'mini_url/base.html' %}
{% block title %}
RaccourcisseurUrl
{% endblock%}
{% block body %}
<h1>Raccourcir une URL </h1>
<form method="post" action="{% url 'afficher' %}">
{% csrf_token %}
{{form.as_p}}
<input type="submit"/>
</form>
{% endblock %}
#liste.html#
{% extends 'mini_url/base.html' %}
{% block title %}
Page RaccourcisseurUrl
{% endblock%}
{% block body %}
<h1>Le raccourcisseur d'URL spécial </h1>
<p></p>Raccourcir une url </p>
<p>Liste des URLs raccourcies : </p>
<ul>
{% for mini in minis %}
<li>{{ mini.url }} via <a href="http://{{ request.get_host }}{% url 'redirection' mini.code %}">
{{ request.get_host } {% url 'redirection' mini.code %} </a>
{% if mini.pseudo %}
par {{ mini.pseudo }}
{% endif %} ({{mini.acces }} accès)
</li>
{% empty %}
<li> Il n'y en pas actuellement </li>
{% endfor %}
</ul>
{% endblock %}
In your list.html most certainly in {% url 'redirection' mini.code %} mini.code has no value.
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 %}
At my home-page I've got exhibited all posts on my blog, but they're sorted incorrectly, from the oldest post to newest(it has to be reversed).
I use querysets to sort posts order by published date in my views.py
def home(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, "home.html", {'posts': posts})
And that's my home.html source code:
{% extends "C:\myapp\blog\templates\base.html" %}
{% block content %}
{% for post in posts %}
<div class="post">
<div class="date">
{{ post.published_date }}
</div>
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endfor %}
{% endblock content %}
Could you help me in reverse these posts?
Thanks in advance.
You want to add a - to the string argument in order_by this will cause your queryset to be in descending order.
def home(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
return render(request, "home.html", {'posts': posts})
Notice the .order_by('-published_date')
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 %}
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)