1

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

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

此外,有时某些评论出现在错误的父项下,有时根本不出现。

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

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']

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

{% 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)

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

4

1 回答 1

1

在这方面得到了很棒的包作者 Craig de Stigter 的一些帮助。似乎问题是由于我rebuild()在更改order_insertion_by特定评论的字段(“点”)后没有在模型树上使用引起的。

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

def save(self, *args, **kwargs):
    Comment.objects.rebuild()
    return super(CommentForm, self).save(*args, **kwargs)
于 2013-08-05T18:40:26.833 回答