[Django]-How does get_comment_permalink in Django's comments framework work?

2👍

So for the comments, shouldn’t it be the same? Shouldn’t the URL simply be a #c1 or something without the /comments/cr/18/1/…? In fact I don’t even know where Django got 18 and 1… From the shortcut method, I understand that 18 is the content_type_id and 1 is the

18 is the content type id, and 1 is the object id. The shortcut view fetches the object from the database using these parameters and redirects to modelobject.get_absolute_url().

Define/fix get_absolute_url() method in your models, this will repair django.contrib.contenttypes.views.shortcut.

That said, it is expected by Django that the url of the model object displays the list of comments for this object. In that case, just add <a name="c{{ comment.id }}"></a> in your single comment HTML.

👤jpic

4👍

The comments framework uses Generic Relations to link Comment objects to your database objects (Order model in your case). Generic relationships allow one object to maintain a relationship with another object without explicitly knowing about it’s class. You can see the fields creating the generic relationship (content_type, object_pk, content_object) for comment here: django.contrib.comments.models

Once a comment has been made and attached to an instance of a particular class (a single Order for example), we need a way to get a link to that particular comment (the permalink). To get a link to a comment, we need to know the URL of the object the comment has been made on (again, the particular Order in your case). This is what get_comment_permalink is doing – it constructs a URL to the object for which a comment has been left on and also attached an anchor link (the #c1 part) to the URL so that the browser jumps to a particular comment on that page.

To do all this it has 3 steps:

  • first figure out what type of object it’s dealing with by looking up the generic relationship. This will leave us with a Order object
  • Now it tries to get the absolute url get_absolute_url of that object. This might be /order/my-order/
  • It constructs that `http://mysite.com/’ part of the URL by using the Sites framework
  • It figures out the #c31 (anchor link to the comment) part of the url

Now we have a full http://mysite.com/order/my-order/c#31 that will bring us to the correct page and show the correct comment

Leave a comment