Answer the question
In order to leave comments, you need to log in
No post found matching the query, what is my mistake?
Hello, I am creating a small blog. I use CBV. When switching to pk(127.0.0.1:8000/detail/1/), the error No post found matching the query occurs, although there are posts in the database. What's my mistake?
models.py
class Post(models.Model):
theme = models.CharField(max_length=100)
post_text = models.CharField(max_length=4000)
pub_date = models.DateTimeField('date published')
def get_absolute_url(self):
return reverse("Blog:index", kwargs={'pk': self.pk}) # реверс - работает без пк kwargs={'pk': self.pk}
def __str__(self):
return self.theme
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.self_description = 'Published recently?'
app_name = 'Blog'
urlpatterns = [
path('detail/', views.IndexView.as_view(), name='index'),
path('create/', views.CreateView.as_view(), name='create'),
path('detail/<int:pk>/', views.DetailView.as_view(), name='detail'),
]
class IndexView(generic.ListView):
queryset = Post.objects.all()
template_name = 'Blog/index.html'
context_object_name = 'latest_post_list'
class DetailView(generic.DetailView):
template_name = "Blog/detail_post.html"
#context_object_name = 'Post'
queryset = Post.objects.all()
class CreateView(generic.CreateView):
model = Post
template_name = 'create_post.html'
fields = ['theme',
'post_text',
'pub_date']
Answer the question
In order to leave comments, you need to log in
class DetailView(generic.DetailView):
template_name = "Blog/detail_post.html"
model = Post
Define the get_object method
from django.shortcuts import get_object_or_404
class DetailView(generic.DetailView):
object = Post
template_name = "Blog/detail_post.html"
def get_object(self, queryset=None):
return get_object_or_404(Post, pk=self.kwargs.get('pk'))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question