我在定制django评论框架方面遇到了问题。我需要添加一个“公司”字段。我已经按照文档,并没有真正到任何地方。它距离工作不远,因为当我向我的settings.py添加COMMENTS_APP ='comments_app'时,'comments'应用程序从管理界面消失了。当我尝试写评论时,它会出现在公司字段中,它会询问您的电子邮件,网址等。
我希望能够查看管理面板中的所有评论以及我添加的公司字段。
我是否需要创建一个admin.py或者我只是缺少一些东西?
以下是我的自定义评论应用的代码:
//模型
from django.db import models
from django.contrib.comments.models import Comment
class CommentWithAddedFields(Comment):
company = models.CharField(max_length=300)
// FORMS.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',如上所述。
我错过了什么吗?
由于
答案 0 :(得分:1)
是的,如果您希望模型显示在django admin中,则需要为自定义评论应用创建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)