Reputation:
Why is this happening? I do everything according to the instructions. I study.
urls.py
from django.conf.urls import url,include
from django.contrib import admin
from . import views
urlpatterns = [
#url(r'^$',views.main,name="main"),
url(r'^post/(?P<id>[0-9]+)/', views.post_detail, name='post_detail'),
]
views.py
from django.shortcuts import render
from django.utils import timezone
from .models import Post
from django.shortcuts import render, get_object_or_404
# Create your views here.
def post_detail(request,id):
post = get_object_or_404(Post, pk=id)
return render(request, 'main/post_detail.html', {'post': post})
post_detail.html
{% extends 'main/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|linebreaksbr }}</p>
</div>
{% endblock %}
What to do? Even instead of id put pk, but nothing helps.
Upvotes: 0
Views: 135
Reputation: 1320
Your urls.py file should work (it worked for me) but you should end this url with $ to prevent matching urls with something after product id with this view.
url(r'^post/(?P<id>[0-9]+)/$', views.post_detail, name='post_detail'),
You can use pdb in post_detail
method to check is called:
def post_detail(request,id):
import pdb
pdb.set_trace()
post = get_object_or_404(Post, pk=id)
return render(request, 'main/post_detail.html', {'post': post})
If method is called that execution should stop on pdb.set_trace()
line. You can resume it with pressing 'c' and ENTER.
pdb is very useful and you should use it first when you have a problem. (Mode details: https://docs.python.org/2/library/pdb.html)
If method is called that it should be problem with lack of post with given id, Otherwise you should make sure that ROOT_URLCONF
from settings are referencing this module.
To check is post with this id existing:
Try this command in django shell:
Post.objects.get(pk=1)
if it returns
Post.DoesNotExist
than you need to create this post using:
Post.objects.create(pk=1, **some_values)
Upvotes: 1