【问题标题】:Writes id instead of name写 id 而不是 name
【发布时间】:2021-08-31 20:08:29
【问题描述】:

我是django新手,遇到这样的问题,写的是id而不是类别名,请问如何解决?附上代码,代码不完整(仅使用过的部分)。我不知道该怎么做了,很可能问题出在views.py中

model.py

    class Category(models.Model):
    category_name = models.CharField(max_length=64, unique=True)
    subscribers = models.ManyToManyField(User, blank=True, null=True)


    class Meta:
        verbose_name = 'Категория'
        verbose_name_plural = 'Категории'

    def __str__(self):
        return self.category_name

class Post(models.Model):
    PostAuthor = models.ForeignKey(Author, on_delete=models.CASCADE)

    PostNews = 'PN'
    PostArticle = 'PA'

    # «статья» или «новость»
    POSITIONS = [
        (PostArticle, 'Статья'),
        (PostNews, 'Новость'),
    ]

    title = models.CharField(max_length=50)
    positions = models.CharField(max_length=2, choices=POSITIONS, default=PostArticle)
    data = models.DateTimeField(auto_now_add=True)
    postCategory = models.ManyToManyField(Category, through='PostCategory')
    previewName = models.CharField(max_length=128)
    text = models.TextField()
    rating = models.SmallIntegerField(default=0)

    def like(self):
        self.rating +=1
        self.save()

    def dislike(self):
        self.rating -=1
        self.save()

    def preview(self):
        return self.text[0:124] + '...'

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 'Пост'
        verbose_name_plural = 'Посты'

    def get_absolute_url(self):
        return f'/news/{self.pk}'

class PostCategory(models.Model):
    pcPost = models.ForeignKey(Post, on_delete=models.CASCADE)
    pcCategory = models.ForeignKey(Category, on_delete=models.CASCADE)

    class Meta:
        verbose_name = 'Пост категория'
        verbose_name_plural = 'Пост категории'

    def __str__(self):
        return f'{str(self.pcPost)}, имеет категорию {str(self.pcCategory)}'

views.py我认为错误就在这里

class new(LoginRequiredMixin, PermissionRequiredMixin, DetailView):
model = Post
template_name = 'new_home.html'
context_object_name = 'new'
permission_required = 'news.view_post'


def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['com_post'] = Comment.objects.filter(commentPost=self.kwargs['pk']).values("commentText")
    context['pc_post'] = PostCategory.objects.filter(pcPost=self.kwargs['pk']).values('pcCategory')
    return context

new_home.html垃圾代码,但我只是在学习

    <!DOCTYPE html>
<html lang="en">
<head>{%extends 'flatpages/default.html'%} {% load custom_filters %}
    <meta charset="UTF-8">
    <title>{%block title%} {{new.title|censor_filter}} {%endblock title%}</title>
</head>
<body>
{%block content%}
<h2>{{new.title|censor_filter}}</h2>
<hr>
<h4>Пост опубликован: {{new.data}}</h4>
<hr>
<h5>{{new.text|censor_filter}}</h5>
<hr>
<h6>Пост опубликовал: {{new.PostAuthor}}</h6>
<hr>
{%for pc in pc_post%}
<button><span style="color: #000000;"><a style="color: #000000;" href="{%url 'category_detail' pc.pcCategory %}">Категория: {{pc.pcCategory}}</a></span></button>
{%endfor%}

{%for comment in com_post%}
<p>Комментарии: {{comment.commentText}}</p>
{%endfor%}

{%endblock content%}
</body>
</html>

应用“新闻”中的 urls.py

from django.urls import path
from .views import *

path('category/<int:pk>/', CategoryDetailView.as_view(), name='category_detail'),
path('category/<int:pk>/subscribe/', subscribe, name='subscribe'),
path('category/<int:pk>/unsubscribe/', unsubscribe, name='unsubscribe'),
path('category/sub/confirm/', SubsConfirm.as_view(), name='sub_confirm'),
path('category/sub/unconfirm/', SubsUnConfirm.as_view(), name='sub_unconfirm'),
path('categories/', CatigoriesView.as_view(), name = 'categories_list'),

【问题讨论】:

    标签: html python-3.x django django-views


    【解决方案1】:

    在您的模板中,使用点符号来获取您想要遵循外键关系的属性。

    所以不要使用{{pc.pcCategory}},而是使用{{pc.pcCategory.category_name}}

    【讨论】:

    • 什么都不输出,只是空虚
    • 是的,抱歉,没有注意到您的查询末尾附加了.values
    【解决方案2】:

    在您看来,您正在使用values 编写查询,这将返回一个字典,其中的值是存储在数据库中的实际值。因此,由于pcCategoryForeignKey,因此存储在数据库中的值是相关实例的id,因此这就是模板中显示的内容。只需删除对values 的调用,它就会按预期工作:

    context['pc_post'] = PostCategory.objects.filter(pcPost=self.kwargs['pk']) # No call to `values`
    

    此外,在您的模板中,您还有以下行,现在会导致错误:

    href="{%url 'category_detail' pc.pcCategory %}"
    

    将其更改为:

    href="{%url 'category_detail' pc.pcCategory.pk %}"
    

    【讨论】:

    • NoReverseMatch at /news/32 Reverse for 'category_detail' with arguments '(,)' 未找到。尝试了 1 种模式:['news/category/(?P[0-9]+)/$']
    • @BlackBlack 将 {%url 'category_detail' pc.pcCategory %} 更改为 {%url 'category_detail' pc.pcCategory.pk %}
    猜你喜欢
    • 1970-01-01
    • 2019-12-29
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    相关资源
    最近更新 更多