Django 评论应用程序,获取内容类型
我正在尝试创建一个评论应用程序,以便在需要的地方使用它,所以我想我必须使用 ContentType
将评论附加到我的项目的不同模型。 所以这里:
我的模型:
class Comment(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
text = models.TextField((u'Текст комментария'))
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
我的视图:
def add_comment(request):
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
new_comment = Comment()
new_comment.text = request.POST['text']
new_comment.content_type = ???
new_comment.object_id = request.POST['object_id']
new_comment.user = request.user
new_comment.save()
return HttpResponseRedirect(request.META['HTTP_REFERER'])
else: ...
如何获取我正在使用的当前模型的内容类型? 我里面有应用程序新闻和模型帖子,所以我想评论我的帖子。
我知道我可以使用 ContentType.objects.get(app_label="news", model="post"),但我得到的是准确的值,所以这样我的评论应用程序就不会是多用途的。
PS抱歉英语不好。
I am trying to create a comments application to use it everywhere where I need it, so I geuss I have to use ContentType
to attach comments to different models of my project.
so here:
my model
:
class Comment(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
text = models.TextField((u'Текст комментария'))
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
my view
:
def add_comment(request):
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
new_comment = Comment()
new_comment.text = request.POST['text']
new_comment.content_type = ???
new_comment.object_id = request.POST['object_id']
new_comment.user = request.user
new_comment.save()
return HttpResponseRedirect(request.META['HTTP_REFERER'])
else: ...
How can I get a content type of the current model I am working with?
I have app NEWS and model Post in it, so I want to comments my Posts.
I know I can use ContentType.objects.get(app_label="news", model="post")
, but I am getting exact value, so in that way my comment app will not be multipurpose.
P.S. sorry for bad English.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查 django.contrib.comments.forms.CommentForm.get_comment_create_data :它返回一个用于创建未保存的评论实例的映射:
所以我猜您正在寻找的行是:
Remenber,
self
是表单实例,self.target_object()
返回当前评论所附加到的实例。Check
django.contrib.comments.forms.CommentForm.get_comment_create_data
: It returns a mapping to be used to create an unsaved comment instance:So I guess that the line your are looking for is:
Remenber,
self
is the form instance, andself.target_object()
returns the instance that the current comment is attached to.