【发布时间】:2020-06-02 08:19:56
【问题描述】:
我是编写程序和使用Django的初学者,现在我想在前端显示类别。我创建了一个名为“主题”的外键作为一个类别。通过输入URL成功访问主题(子类别)和帖子(使用pk)。虽然 URL 配置是有效的,但我不知道如何使用模板标签将它放在前端。我想创建一个目录,当我点击某个目录时,会显示这些在特定“主题”下的帖子。我通过《Django for初学者》和《Django for Professional》这本书学习了 Django,但是它没有涵盖这样的主题。我看在线教程,我很困惑和沮丧。 (我的Django版本是3.0.0)
感谢您的帮助:)
类似http://127.0.0.1:8000/django/1的文章网址
话题(FK)(PK后)
我的模特
from django.db import models
from ckeditor.fields import RichTextField
class Topic(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, default='self.name')
def get_absolute_url(self):
return reverse('topic',
args=[self.slug])
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=50)
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
content = RichTextField()
topic = models.ForeignKey(Topic, default=1, on_delete=models.SET_DEFAULT)
def __str__(self):
return self.title
查看
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post
class Home(ListView):
model = Post
template_name = 'home.html'
class TopicList(ListView):
model = Post
template_name = 'topiclist.html'
class PostDetail(DetailView):
model = Post
template_name = 'detail.html'
# Create your views here.
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Post
class Home(ListView):
model = Post
template_name = 'home.html'
class TopicList(ListView):
model = Post
template_name = 'topiclist.html'
class PostDetail(DetailView):
model = Post
template_name = 'detail.html'
网址
from django.urls import path
from .views import Home, PostDetail, TopicList
urlpatterns = [
path('', Home.as_view(), name='home'),
path('<slug:topic>/<int:pk>', PostDetail.as_view(), name='detail'),
path('<slug:topic>/', TopicList.as_view(), name='topiclist'),
【问题讨论】:
标签: django python-3.x django-templates