Skip to main content
 首页 » 编程设计

python之自定义 Django 评论应用程序

2025年05月04日38java哥

我在自定义 Django 评论框架时遇到问题。我需要添加一个“公司”字段。我已经按照文档进行操作,但并没有真正取得进展。它离工作不远,因为当我将 COMMENTS_APP = 'comments_app' 添加到我的 settings.py 时,'comments' 应用程序从管理界面中消失了。当我尝试写评论时,它会出现公司字段,要求您提供电子邮件、网址等。

我希望能够在管理面板中查看所有评论以及我添加的公司字段。

我需要创建一个 admin.py 还是我只是缺少了一些东西?

这是我的自定义评论应用程序代码:

//型号

 from django.db import models 
    from django.contrib.comments.models import Comment 
 
    class CommentWithAddedFields(Comment): 
        company = models.CharField(max_length=300) 

//表格.py

from django import forms 
from django.contrib.comments.forms import CommentForm 
from comments_app.models import CommentWithAddedFields 
 
class CommentFormWithAddedFields(CommentForm): 
    company = forms.CharField(max_length=300) 
 
 
    def get_comment_model(self): 
 
        return CommentWithAddedFields 
 
 
    def get_comment_create_data(self): 
 
        data = super(CommentFormWithAddedFields, self).get_comment_create_data() 
        data['company'] = self.cleaned_data['company'] 
        return data 

//__init.py

from comments_app.models import CommentWithAddedFields 
from comments_app.forms import CommentFormWithAddedFields 
 
def get_model(): 
    return CommentWithAddedFields 
 
 
def get_form(): 
    return CommentFormWithAddedFields 

我已经在我的 settings.py 文件中添加了该应用程序,并添加了 COMMENTS_APP = 'comments_app' 如上所述。

我是不是漏掉了什么?

谢谢

请您参考如下方法:

是的,如果您希望您的模型出现在 django 管理中,您需要为您的自定义评论应用程序创建一个 admin.py。您应该能够子类化 CommentsAdmin,并根据需要进行自定义。

from django.contrib import admin 
from django.utils.translation import ugettext_lazy as _, ungettext 
from django.contrib.comments.admin import CommentsAdmin 
from django.contrib.comments import get_model 
 
from comments_app.models import CommentWithAddedFields 
 
class MyCommentsAdmin(CommentsAdmin): 
    # Same fieldsets as parent admin, but include 'company' 
    fieldsets = ( 
        (None, 
           {'fields': ('content_type', 'object_pk', 'site')} 
        ), 
        (_('Content'), 
           {'fields': ('user', 'user_name', 'user_email', 'user_url', 'company', 'comment')} 
        ), 
        (_('Metadata'), 
           {'fields': ('submit_date', 'ip_address', 'is_public', 'is_removed')} 
        ), 
     ) 
 
# Only register the admin if the comments model is CommentWithAddedFields 
# The equivalent section in django.contrib.comments.admin is what prevents  
# the admin from being registered when you set COMMENTS_APP = 'comments_app'  
# in your settings file 
if get_model() is CommentWithAddedFields: 
    admin.site.register(CommentWithAddedFields, MyCommentsAdmin)