【问题标题】:Trouble using django-mptt for nested comment system在嵌套评论系统中使用 django-mptt 时遇到问题
【发布时间】:2013-08-03 15:46:59
【问题描述】:

我正在尝试使用 django-mptt 设置一个简单的嵌套评论系统,但遇到了一些问题。如果有人可以看看并告诉我我做错了什么,我将非常感激。

到目前为止,我只为特定帖子设置了 cmets 的显示;任何创建/更新/删除暂时都是通过管理员进行的。我遇到的一个问题是,有时当我尝试在管理员中创建/更新/删除时,我得到属性错误“'NoneType' 对象没有属性'tree_id'”。另一个是通过管理员更改评论实例的“order_insertion_by”(“points”字段)中指定的字段的整数值有时会导致ValueError“cache_tree_children以错误的顺序传递节点”当我导航到应该的页面时显示帖子和 cmets。

此外,有时某些 cmets 出现在错误的父级下,有时根本不出现。

以下是我的评论模型的相关部分:

class Comment(MPTTModel):
    posting = models.ForeignKey(Posting)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
    points = models.IntegerField(
        default=0,
    )

    class MPTTMeta:
        order_insertion_by = ['points']

以及我用来显示特定帖子的 cmets 的模板的相关部分:

{% load mptt_tags %}
{% with posting.comment_set.all as comments %}
<ul class="root">
    {% recursetree comments %}
        <li>
            {{ node.message }}
            {% if not node.is_leaf_node %}
                <ul class="children">
                    {{ children }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>
{% endwith %}

最后,我的整个 admin.py 文件,因为我觉得部分问题可能是由我通过管理员更改的内容引起的:

from django.contrib import admin
from django.forms import ModelForm, Textarea
from postings.models import Posting, Comment

class PostingForm(ModelForm):

    class Meta:

        model = Posting
        widgets = {
            'title': Textarea(attrs={'cols': 75, 'rows': 5}),
            'message': Textarea(attrs={'cols': 75, 'rows': 15}),
        }

class CommentForm(ModelForm):

    class Meta:

        model = Comment
        widgets = {
            'message': Textarea(attrs={'cols': 75, 'rows': 15}),
        }

class CommentInline(admin.TabularInline):
    model = Comment
    form = CommentForm

class PostingAdmin(admin.ModelAdmin):
    inlines = [CommentInline]
    list_display = ('title', 'posted', 'variety', 'points', 'user')
    form = PostingForm

admin.site.register(Posting, PostingAdmin)

非常感谢您对此提供的任何帮助。

【问题讨论】:

    标签: python django django-mptt


    【解决方案1】:

    从出色的包作者 Craig de Stigter 那里得到了一些帮助。似乎问题是由于我在更改特定 cmets 的 order_insertion_by 字段(“点”)后未在模型树上使用 rebuild() 引起的。

    根据他的建议,我修改了我的评论模型表单的 save() 方法以包括模型的重建:

    def save(self, *args, **kwargs):
        Comment.objects.rebuild()
        return super(CommentForm, self).save(*args, **kwargs)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-30
      • 2014-05-07
      • 2013-03-10
      • 2018-05-24
      • 1970-01-01
      • 2011-07-13
      • 2014-07-11
      相关资源
      最近更新 更多