Ошибка, не отображающая подробную страницу в Django 2.0

#django #url #django-models #slug #slugify

#django #url #django-модели #ошибка #slugify

Вопрос:

Каков наилучший способ использовать slug в этом случае и заставить его работать должным образом. Я вижу, что URL-адрес в браузере отображает запрошенные элементы, но я не могу отобразить подробную страницу. Я не могу найти, откуда возникает проблема. Когда я обращаюсь к ‘page_detail’, URL-адрес ‘http://127.0.0.1:8000/posts/2019/03/23/greetings /‘, который является правильным на основе моих входных данных, но django выдает ошибку при рендеринге страницы. Ошибка: TypeError: post_detail() got an unexpected keyword argument 'slug'

Модель:

 class Post(models.Model):
       STATUS_CHOICES = (
           ('draft', 'Draft'),
           ('published', 'Published'),
       )
       title = models.CharField(max_length=250)
       slug = models.SlugField(max_length=250,
                               unique_for_date='publish')
       author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blog_posts')
       body = models.TextField()
       publish = models.DateTimeField(default=timezone.now)
       created = models.DateTimeField(auto_now_add=True)
       updated = models.DateTimeField(auto_now=True)
       status = models.CharField(max_length=10,
                                 choices=STATUS_CHOICES,
                                 default='draft')

       published = PublishedManager()   # Custom Model Manager

       def get_absolute_url(self):
        ''' Canonical URL for post detail.'''
        return reverse('snippets:post-detail',
                        args=[self.publish.year,
                                self.publish.strftime('%m'),
                                self.publish.strftime('%d'),
                                self.slug])

       class Meta:
           ordering = ('-publish',)

def __str__(self):
    return self.title
  

URL

 app_name = 'snippets'
urlpatterns = [ 
    path('posts/', views.post_list, name='post-list'),
    path('posts/<int:year>/<int:month>/<int:day>/<slug:slug>/', views.post_detail, name='post-detail'),
]
  

число просмотров

 def post_list(request):
    posts = Post.published.all()
    context = {'posts': posts}
    return render(request, 'snippets/list.html', context)

def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post, slug=post, 
                                status='published',
                                publish__year=year,
                                publish__month=month,
                                publish__day=day)
    return render(request, 'snippets/detail.html', {'post':post})
  

post_list HTML

 {% extends "base.html" %}
   {% block title %}My Blog{% endblock %}
   {% block content %}
     <h1>Blog</h1>
     {% for post in posts %}
       <h2>
         <a href="{{ post.get_absolute_url }}">
           {{ post.title }}
         </a>
       </h2>
       <p class="date">
         Published {{ post.publish }} by {{ post.author }}
       </p>
       {{ post.body|truncatewords:30|linebreaks }}
   {% endfor %}
   {% endblock %}

  

post_detail HTML

 {% extends "base.html" %}
   {% block title %}{{ post.title }}{% endblock %}
   {% block content %}
     <h1>{{ post.title }}</h1>
     <p class="date">
       Published {{ post.publish }} by {{ post.author }}
     </p>
     {{ post.body|linebreaks }}
   {% endblock %}
  

Я все еще застрял. Любая помощь была бы высоко оценена.

Ответ №1:

попробуйте изменить свой views.py для

 def post_detail(request, year, month, day, slug):
post = get_object_or_404(Post, slug=slug, 
                            status='published',
                            publish__year=year,
                            publish__month=month,
                            publish__day=day)
return render(request, 'snippets/detail.html', {'post':post})