简体   繁体   English

我的博客网站上的类别有问题

[英]Problem with categories on my blog website

I have added categories and everything but I can't see any posts in my categories.我添加了类别和所有内容,但在我的类别中看不到任何帖子。 When I open for example http://localhost:8000/category/sport/ it is showing no posts...例如,当我打开 http://localhost:8000/category/sport/ 时,它没有显示任何帖子...

my urls.py:我的网址.py:


from django.urls import path
#from . import views
from .views import HomeView , ArticleDetailView, AddPostView, UpdatePostView, DeletePostView, CategoryView

urlpatterns = [
    #path('', views.home, name="homepage"),
    path('', HomeView.as_view(), name = 'home'),
    path('article/<int:pk>', ArticleDetailView.as_view(), name = 'article-details'),
    path('add_post/', AddPostView.as_view(), name = 'add_post'),
    path('article/edit/<int:pk>', UpdatePostView.as_view(), name = 'update_post'),
    path('article/<int:pk>/delete', DeletePostView.as_view(), name = 'delete_post'),
    path('category/<str:categories>/', CategoryView, name='category'),
]

my models.py:我的模型.py:

from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from datetime import datetime, date

class Category(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name 

    def get_absolute_url(self):
        #return reverse('article-details', args=(str(self.id)))
        return reverse('home')


class Post(models.Model):
    title = models.CharField(max_length=255)
    title_tag = models.CharField(max_length=255, default="YNTN")
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()
    post_date = models.DateField(auto_now_add=True)
    category = models.CharField(max_length=255, default="uncategorized")

    def __str__(self):
        return (self.title + " | " + str(self.author))

    def get_absolute_url(self):
        return reverse("home")

m

y views.py: y views.py:


from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post, Category
from .forms import PostForm, EditForm
from django.urls import reverse_lazy

#def home(request):
#    return render(request, 'home.html', {})
    

class HomeView(ListView):
    model = Post
    template_name = 'home.html'
    #ordering = ['-id']
    ordering = ['-post_date']

def CategoryView(request, categories):
    category_posts = Post.objects.filter(category=categories)
    return render(request, "categories.html", {"categories": categories, 'category_posts': category_posts})

class ArticleDetailView(DetailView):
    model = Post
    template_name = 'article.details.html'

class AddPostView(CreateView):
    model = Post
    form_class = PostForm
    template_name = 'add_post.html'
    #fields = '__all__'
    #fields = ('title', 'body')

class UpdatePostView(UpdateView):
    model = Post
    form_class = EditForm
    template_name = 'update_post.html'
    #fields = ('title', 'title_tag', 'body')

class DeletePostView(DeleteView):
    model = Post
    template_name = 'delete_post.html'
    success_url = reverse_lazy('home')

my categories.html:我的类别.html:


{% extends 'base.html' %}

{% block content %}
<head>
    <title>{{ categories }} category</title>
</head>

<h1>{{ categories }} category</h1>
<hr>

{% for post in category_posts %}
<ul>
    <li>
        <a href="{% url 'article-details' post.pk %}">
            {{ post.title }}</a> - 
        {{ post.category }} - 
        {{ post.author.first_name }}
        {{ post.author.last_name }} - {{ post.post_date }}<br/>
        <!-- <small>{{ post.body | slice:":359" | safe }}</small> -->

        {% if user.is_authenticated %}
        <small><a href="{% url 'update_post' post.pk %}"> (Edit) </a></small> <small><a
            href="{% url 'delete_post' post.pk %}">(Delete)</a></small> <br/>
        {% endif %}
    </li>
</ul>
{% endfor %}

{% endblock %}

my forms.py:我的 forms.py:


from django import forms
from .models import Post, Category

choices = Category.objects.all().values_list('name', 'name')

choice_list = []

for item in choices:
    choice_list.append(item)

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'title_tag', 'author', 'category', 'body')

        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter the title of your article'}),
            'title_tag': forms.TextInput(attrs={'class': 'form-control'}),
            'author': forms.Select(attrs={'class': 'form-control',}),
            'category': forms.Select(choices=choice_list , attrs={'class': 'form-control',}),
            'body': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Enter the content of your article'}),
        }

class EditForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'title_tag', 'author', 'body')

        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter the title of your article'}),
            'title_tag': forms.TextInput(attrs={'class': 'form-control'}),
            'author': forms.Select(attrs={'class': 'form-control',}),
            'body': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Enter the content of your article'}),
        }

Please help, it's important to me:D I'm really stuck.请帮忙,这对我很重要:D我真的被困住了。 It is my first StackOverflow post:D这是我的第一篇 StackOverflow 帖子:D

The proper way to resolve, is to associate Post model with a Category :正确的解决方法是将Post model 与Category相关联:

models.py模型.py

class Post(models.Model):
    title = models.CharField(max_length=255)
    title_tag = models.CharField(max_length=255, default="YNTN")
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()
    post_date = models.DateField(auto_now_add=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE) # this line

It is fine to use <str:category_name> but note that the names MUST correspond.可以使用<str:category_name>但请注意名称必须对应。

urls.py网址.py

path('category/<str:category_name>/', category_view, name='category'),

Beware of good practices when writing code.编写代码时要注意良好做法。 In Python classes uses CamelCase and functions snake_case .Python类中使用CamelCase和函数snake_case

views.py:意见.py:

from django.shortcuts import get_list_or_404

def category_view(request, category_name):
    category_posts =  get_list_or_404(Post, category__name=category_name)

    return render(request, "categories.html", {'category_posts': category_posts})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM