3

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.

Andrew_CS
  • 2,542
  • 1
  • 18
  • 38
Sevalad
  • 69
  • 6

1 Answers1

3

Check django.contrib.comments.forms.CommentForm.get_comment_create_data: It returns a mapping to be used to create an unsaved comment instance:

return dict(
    content_type = ContentType.objects.get_for_model(self.target_object),
    object_pk    = force_unicode(self.target_object._get_pk_val()),
    user_name    = self.cleaned_data["name"],
    user_email   = self.cleaned_data["email"],
    user_url     = self.cleaned_data["url"],
    comment      = self.cleaned_data["comment"],
    submit_date  = datetime.datetime.now(),
    site_id      = settings.SITE_ID,
    is_public    = True,
    is_removed   = False,
)

So I guess that the line your are looking for is:

content_type = ContentType.objects.get_for_model(self.target_object),

Remenber, self is the form instance, and self.target_object() returns the instance that the current comment is attached to.

Armando Pérez Marqués
  • 5,661
  • 4
  • 28
  • 45