Django类别无法正常运作href无效

时间:2019-09-13 18:47:55

标签: python django django-views

我制作了一个脚本来显示一个类别中的所有帖子,因此,当我尝试打开一个类别时,它没有打开页面并显示文章页面,我遵循了制作此代码的教程,即链接是:https://www.youtube.com/watch?v=o6yYygu-vvk

Models.py

from django.db import models
from django import forms
from django.contrib.auth.models import User
from django.urls import reverse

# Categorie
class Category(models.Model):
    class Meta:
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    name = models.CharField('Titolo', max_length = 250)
    slug = models.SlugField(max_length = 250, unique = True)
    desc = models.TextField('Descrizione', max_length=10000, blank=True)

    def get_absolute_url(self):
        return reverse("blog:CategoryList", args=[self.slug])


    def __str__(self):
      return self.name
# Articles
class Article(models.Model):
    class Meta:
        verbose_name = 'Articolo'
        verbose_name_plural = 'Articoli'
    '''
    Classe per creare articoli generali con media
    '''
    title = models.CharField('Titolo', max_length=100)
    author = models.ForeignKey(User, on_delete=models.CASCADE,)
    category = models.ForeignKey (Category, on_delete=models.CASCADE)
    desc = models.CharField('Descrizione', max_length=10000, blank=True)
    text = models.TextField('Testo', max_length=10000, blank=True)
    image = models.ImageField('Foto', blank=True, upload_to="img")
    data = models.DateTimeField('Data di pubblicazione', blank=True)
    slug = models.SlugField(max_length = 250, null = True, blank = True, unique=True)

    class Meta: # Order post by date
        ordering = ['-data',]

    def __str__(self):
       return "Crea un nuovo articolo"

Views.py

from django.shortcuts import render, get_object_or_404
from django.shortcuts import render
from django.http import HttpResponse
from .models import *
from django.views.generic import View
from django.views import generic


def index(request): # HomePage
   articles = Article.objects.all().order_by('-data')[0:3] # Show last 3 articles
   return render(request, 'blog/index.php', {'articles':articles})

# Post

def PostList(request): # Articles List
  articles = Article.objects.all().order_by('-data')
  return render(request, 'blog/post/PostList.php',{'articles':articles})

class PostDetail(generic.DetailView): #Single Article
   model = Article
   template_name = 'blog/post/post_detail.php'

# Category

def Categories(request): # Category List
  categories = Category.objects.all()
  return render(request, 'blog/category/category.php',{'categories':categories})

def CategoryList(request, slug): # Show post by category
  categories = Category.objects.all()
  articles = Article.objects.all()
  if slug:
     category = get_object_or_404(Category, slug=slug)
     articles = articles.filter(category=slug)

  template = 'blog/category/single_category.php'
  context = {'categories':categories, 'articles':articles, 'category': category}

  return render(request, template, context)

Urls.py

from django.conf.urls import url
from . import views
from django.contrib import admin
from django.views.generic import ListView, DetailView
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path

urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^$', views.index, name='index'), # Index
  url(r'^all-articles$', views.PostList, name='PostList'), # All Posts
  url(r'^category', views.Categories, name='category'), # All Category
  url('<slug: slug>/', views.CategoryList, name='category_list'), # Show post by category
  path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), # Single Posts

]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += staticfiles_urlpatterns()

post_detail.php

{% extends 'blog/layout.php' %} <!-- Import Content -->
{% block content %} <!-- Start Content -->
<!-- Articles -->
  <div class="article">
    {% if article.image %}
      <img src="{{article.image.url}}" alt="" class="">
    {% endif %}
    <div class="article__text">
       <h1>{% block title %} {{ object.title }} {% endblock title %}</h1>
       <p class="article_info"> Scritto da <a href="#">{{ article.author }}</a> il {{ 
article.data }}</p>
       <p class=" article_desc">{{ article.desc }}</p>
       <p class=" article_content">{{ article.text }}</p>
       <p class=" article_category">category: <a href="{{ articles.category.get_absolute_url 
}}">
         {{ article.category }}</a></p>
    </div>
</div>
{% endblock content %}

single_category.php

{% extends 'blog/layout.php' %} <!-- Import Content -->
<!-- Content -->
{% block content %}
 <h1>{{ category.name }}</h1>
 {% for article in articles %}
 <!--CARDS -->
   <section class="cards"clearfix> <a href="{% url 'post_detail' article.slug  %}">
    <div class="card">
      {% if article.image %}
      <img src="{{article.image.url}}" alt="" class="card__img">
      {% endif %}
       <div class="card__txt">
        <h3 class="card__title">{{article.title}}</h3>
        <p class="date__article"> by {{article.author}}</p>
        <p class="card__text">{{article.desc}}</p>
       </div>
    </div>
   </a>
   </section>
   {% endfor  %}
  {% endblock %}

1 个答案:

答案 0 :(得分:0)

您返回类别网址的函数是错误的,因为“ CategoryList”的名称不存在

class Category():
#---- your properties definition

def get_absolute_url(self):
    #bad return reverse("blog:CategoryList", args=[self.slug])
    return reverse("blog:category_list", args=[self.slug])

在您的urls.py

  url('<slug: slug>/', views.CategoryList, name='category_list'), # Show post by category

category_list 被定义为您网址中的名称,而不是〜CategoryList〜

AND 您将相同的URL用于帖子和类别列表

url('<slug: slug>/', views.CategoryList, name='category_list'), # Show post by category
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), 

AND 您正在以相同的定义混合urlpath。 因此,您可能正在使用django 2.x并阅读django 1.x教程。

另一种想法(对开发人员进行了评论)... html文件作为php的扩展名不好,php是一种“程序语言”,而html是另一件事...但是,您可以使用任何扩展名。