繁体   English   中英

使用django-mptt进行嵌套注释系统时出现问题

[英]Trouble using django-mptt for nested comment system

我正在尝试使用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文件,因为我觉得问题的一部分可能是由于我通过admin进行更改而引起的:

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)

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

得到了很棒的软件包作者Craig de Stigter的帮助。 似乎问题是由我对特定注释的order_insertion_by字段(“ points”)进行更改后,没有在模型树上使用rebuild()引起的。

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

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

暂无
暂无

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

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